using IRaCIS.Application.Interfaces;
using IRaCIS.Application.Contracts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Infra.EFCore.Common;

namespace IRaCIS.Application.Services
{
    /// <summary>
    /// 数据字典-基础数据维护
    /// </summary>

    [ApiExplorerSettings(GroupName = "Common")]
    public class DictionaryService : BaseService, IDictionaryService
    {
        private readonly IRepository<Dictionary> _dicRepository;
        private readonly IRepository<TrialDictionary> _trialDictionaryRepository;
        private readonly IRepository<Trial> _trialRepository;
        private readonly IRepository<SystemCriterionDictionaryCode> _systemCriterionDictionaryCodeRepository;
        private readonly IRepository<TrialCriterionDictionaryCode> _trialCriterionDictionaryCodeRepository;
		private readonly IRepository<ReadingTrialCriterionDictionary> _readingTrialCriterionDictionaryRepository;

		private readonly IRepository<ReadingSystemCriterionDictionary> _readingCriterionDictionaryRepository;
		private readonly IRepository<ReadingQuestionCriterionSystem> _readingQuestionCriterionSystem;
        private readonly IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrial;
        private readonly IReadingQuestionService _readingQuestionService;

        public DictionaryService(IRepository<Dictionary> sysDicRepository, IRepository<TrialDictionary> trialDictionaryRepository,
           IRepository<Trial> trialRepository,

             IRepository<SystemCriterionDictionaryCode> systemCriterionDictionaryCodeRepository,
                   IRepository<TrialCriterionDictionaryCode> trialCriterionDictionaryCodeRepository,
						 IRepository<ReadingTrialCriterionDictionary> readingTrialCriterionDictionaryRepository,
			 IRepository<ReadingSystemCriterionDictionary> readingCriterionDictionaryRepository,
                 IRepository<ReadingQuestionCriterionSystem> readingQuestionCriterionSystem,
                   IRepository<ReadingQuestionCriterionTrial> readingQuestionCriterionTrial,
            IReadingQuestionService readingQuestionService


            )
        {
            _dicRepository = sysDicRepository;
         
            _trialDictionaryRepository = trialDictionaryRepository;
       
            _trialRepository = trialRepository;
            this._systemCriterionDictionaryCodeRepository = systemCriterionDictionaryCodeRepository;
            this._trialCriterionDictionaryCodeRepository = trialCriterionDictionaryCodeRepository;
			this._readingTrialCriterionDictionaryRepository = readingTrialCriterionDictionaryRepository;
			this._readingCriterionDictionaryRepository = readingCriterionDictionaryRepository;
            this._readingQuestionCriterionSystem = readingQuestionCriterionSystem;
            this._readingQuestionCriterionTrial = readingQuestionCriterionTrial;
            this._readingQuestionService = readingQuestionService;
        }

        /// <summary>
        /// 添加bool
        /// </summary>
        /// <param name="addOrEditBasic"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddBoolDic(AddOrEditBasicDic addOrEditBasic)
        {

            var entity = await _dicRepository.InsertFromDTOAsync(addOrEditBasic);



            var child1 = entity.Clone();
            child1.Id = Guid.Empty;
            child1.Code = "true";
            child1.ParentId = entity.Id;

            entity.ChildList.Add(child1);

            var child2 = entity.Clone();
            child2.Id = Guid.Empty;
            child2.Code = "false";
            child2.ParentId = entity.Id;

            entity.ChildList.Add(child2);

            await _dicRepository.SaveChangesAsync();
            return ResponseOutput.Ok(entity.Id.ToString());
        }


        /// <summary>
        /// 添加字典 的同时 一起添加子项  --New  
        /// </summary>
        /// <param name="addBasicDicAndChild"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddBasicDicAndChild(AddBasicDicAndChild addBasicDicAndChild)
        {
            var verifyExp1 = new EntityVerifyExp<Dictionary>()
            {
                VerifyExp = t => t.Code == addBasicDicAndChild.Code && t.ParentId == null,
                VerifyMsg = $"已有{addBasicDicAndChild.Code}名称的字典",
                IsVerify = true
            };


            var entity = await _dicRepository.InsertFromDTOAsync(addBasicDicAndChild, false, verifyExp1);

            var childList = _mapper.Map<List<Dictionary>>(addBasicDicAndChild.ChildList);

            foreach (var item in childList)
            {
                item.DataTypeEnum = addBasicDicAndChild.DataTypeEnum;
                item.ParentId = entity.Id;
            }

            await _dicRepository.AddRangeAsync(childList);

            await _dicRepository.SaveChangesAsync();
            return ResponseOutput.Ok(entity.Id.ToString());
        }

        /// <summary>
        /// New  查询条件  
        /// </summary>
        /// <param name="basicDicQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<BasicDicView>> GetBasicDicList(BasicDicQuery basicDicQuery)
        {

            var systemBasicDataQueryable = _dicRepository.Where(t => t.ParentId == null)
                .WhereIf(!string.IsNullOrEmpty(basicDicQuery.Code), t => t.Code.Contains(basicDicQuery.Code!))
                .WhereIf(!string.IsNullOrEmpty(basicDicQuery.keyInfo), t => t.Description.Contains(basicDicQuery.keyInfo!)
                || t.Code.Contains(basicDicQuery.keyInfo!)
                || t.ChildList.Any(u => u.ValueCN.Contains(basicDicQuery.keyInfo!))
                || t.ChildList.Any(u => u.Description.Contains(basicDicQuery.keyInfo!))
                || t.ChildList.Any(u => u.Value.Contains(basicDicQuery.keyInfo!)))

                .WhereIf(basicDicQuery.ConfigTypeId != null, t => t.ConfigTypeId == basicDicQuery.ConfigTypeId!)
                .WhereIf(basicDicQuery.DataTypeEnum != null, t => t.DataTypeEnum == basicDicQuery.DataTypeEnum)
                .WhereIf(basicDicQuery.DataTypeEnum == null, t => t.DataTypeEnum != DicDataTypeEnum.Config)

                .ProjectTo<BasicDicView>(_mapper.ConfigurationProvider);

            return await systemBasicDataQueryable.ToPagedListAsync(basicDicQuery.PageIndex, basicDicQuery.PageSize, String.IsNullOrEmpty(basicDicQuery.SortField) ? nameof(BasicDicView.ConfigType) : basicDicQuery.SortField, basicDicQuery.Asc, String.IsNullOrEmpty(basicDicQuery.SortField), new[] { nameof(BasicDicView.ConfigType), nameof(BasicDicView.ShowOrder) });
        }


        /// <summary>
        /// 添加和编辑
        /// </summary>
        /// <param name="addOrEditBasic"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateBasicDic(AddOrEditBasicDic addOrEditBasic)
        {
            var verifyExp1 = new EntityVerifyExp<Dictionary>()
            {
                VerifyExp = t => t.Code == addOrEditBasic.Code && t.ParentId == addOrEditBasic.ParentId,
                //---------- $"已有{addOrEditBasic.Code}名称的字典"
                VerifyMsg = _localizer["Dictionary_DictionaryName", addOrEditBasic.Code],
                IsVerify = addOrEditBasic.ParentId == null
            };


            //// 验证阅片标准是否可禁用
            //if (!addOrEditBasic.IsEnable&&addOrEditBasic.Id!=null)
            //{
            //    var result = await _readingQuestionService.SetSystemCriterionDisable(addOrEditBasic.Id.Value,addOrEditBasic.ParentId);
            //    if (!result.IsSuccess)
            //    {
            //        return result;
            //    }
            //}


            if (addOrEditBasic.Id != null && addOrEditBasic.ParentId == null)
            {
                await _dicRepository.UpdatePartialFromQueryAsync(t => t.ParentId == addOrEditBasic.Id, c => new Dictionary() { DataTypeEnum = addOrEditBasic.DataTypeEnum });

                //await _dicRepository.BatchUpdateNoTrackingAsync(t => t.ParentId == addOrEditBasic.Id, c => new Dictionary() { DataTypeEnum = addOrEditBasic.DataTypeEnum });
            }

            var entity = await _dicRepository.InsertOrUpdateAsync(addOrEditBasic, true, verifyExp1);



            await _dicRepository.SaveChangesAsync();
            return ResponseOutput.Ok(entity.Id.ToString());
        }

        /// <summary>
        /// 获取子项数组
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        [HttpGet("{parentId:guid}")]
        public async Task<List<BasicDicView>> GetChildList(Guid parentId)
        {
            return await _dicRepository.Where(t => t.ParentId == parentId)
                .OrderBy(t => t.ShowOrder).ProjectTo<BasicDicView>(_mapper.ConfigurationProvider).ToListAsync();
        }



        /// <summary> 删除字典数据 </summary>
        [HttpDelete("{id:guid}")]
        public async Task<IResponseOutput> DeleteDictionary(Guid id)
        {
            if (await _readingCriterionDictionaryRepository.AnyAsync(x => x.DictionaryId == id))
            {
                await _readingCriterionDictionaryRepository.BatchDeleteNoTrackingAsync(t => t.DictionaryId == id);
                //---当前字典在标准中被引用,不允许删除！
                //return ResponseOutput.NotOk(_localizer["Dictionary_DictionaryDeletion"]);
            }

			if (await _readingTrialCriterionDictionaryRepository.AnyAsync(x => x.DictionaryId == id))
			{
				await _readingTrialCriterionDictionaryRepository.BatchDeleteNoTrackingAsync(t => t.DictionaryId == id);
				//---当前字典在标准中被引用,不允许删除！
				//return ResponseOutput.NotOk(_localizer["Dictionary_DictionaryDeletion"]);
			}

			if (await _dicRepository.AnyAsync(t => t.ParentId == id))
            {
                //---有子项数据，不允许直接删除！
                return ResponseOutput.NotOk(_localizer["Dictionary_SubitemDeletion"]);
            }


            if (await _trialDictionaryRepository.AnyAsync(t => t.DictionaryId == id) ||
                await _trialRepository.AnyAsync(t => t.ReviewModeId == id))
            {
                //---当前条目已经在项目信息中被引用。
                return ResponseOutput.NotOk(_localizer["Dictionary_ProjectReference"]);
            }


            var success = await _dicRepository.BatchDeleteNoTrackingAsync(t => t.Id == id);
            return ResponseOutput.Result(success);
        }

        /// <summary>
        /// 传递父亲 code  字符串  数组  返回多个下拉框数据
        /// </summary>
        /// <param name="searchArray"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Dictionary<string, List<BasicDicSelectCopy>>> GetBasicDataSelect(string[] searchArray)
        {

            var searchList = await _dicRepository.Where(t => searchArray.Contains(t.Parent.Code) && t.ParentId != null && t.IsEnable).ProjectTo<BasicDicSelectCopy>(_mapper.ConfigurationProvider).ToListAsync();

            return searchList.GroupBy(t => t.ParentCode).ToDictionary(g => g.Key, g => g.OrderBy(t => t.ShowOrder).ToList());

        }

        /// <summary>
        /// 根据父亲Code  获取单个下拉框数据
        /// </summary>
        /// <param name="searchKey"></param>
        /// <returns></returns>
        public async Task<List<BasicDicSelect>> GetBasicDataSelect(string searchKey)
        {
            var searchList = await _dicRepository.Where(t => t.Parent.Code == searchKey && t.ParentId != null && t.IsEnable).ProjectTo<BasicDicSelect>(_mapper.ConfigurationProvider).ToListAsync();

            return searchList;
        }




        /// <summary>
        /// 根据父亲字典分组  获取子项
        /// </summary>
        /// <param name="searchKey"></param>
        /// <returns></returns>
        public async Task<List<BasicDicSelect>> GetBasicConfigSelect(string searchKey)
        {
            var searchList = await _dicRepository.Where(t => t.ConfigDictionary.Code == searchKey && t.ParentId == null && t.IsEnable).ProjectTo<BasicDicSelect>(_mapper.ConfigurationProvider).OrderBy(x => x.ShowOrder).ToListAsync();

            return searchList;
        }

        /// <summary>
        /// 获取标准字典
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetCriterionDictionaryListOutDto>> GetCriterionDictionaryList(GetCriterionDictionaryListInDto inDto)
        {
            var criterionCodes = await _systemCriterionDictionaryCodeRepository.Where(x => x.SystemCriterionId == inDto.SystemCriterionId).ToListAsync();

            var parentCodes = await _readingCriterionDictionaryRepository.Where(x => x.CriterionId == inDto.SystemCriterionId).Select(x => x.ParentCode).ToListAsync();


            var codes = criterionCodes.Select(x => x.Code).ToList();

            var dictionaryList = await _dicRepository.Where(x => codes.Contains(x.Code) && x.ParentId == null)
                .OrderBy(x => x.ShowOrder).Select(x => new GetCriterionDictionaryListOutDto()
                {
                    Code = x.Code,
                    ShowOrder = x.ShowOrder,
                    Description = x.Description
                }).ToListAsync();

            dictionaryList.ForEach(x =>
            {
                x.Count = parentCodes.Count(y => y == x.Code);
                x.Id = criterionCodes.Where(y => y.Code == x.Code).Select(x => x.Id).FirstOrDefault();
            });

            return dictionaryList;
        }


        /// <summary>
        /// 获取标准字典
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetCriterionDictionaryListOutDto>> GetTrialCriterionDictionaryList(GetTrialCriterionDictionaryListInDto inDto)
        {
            var criterionCodes = await _trialCriterionDictionaryCodeRepository.Where(x => x.TrialCriterionId == inDto.TrialCriterionId).ToListAsync();

            var parentCodes = await _readingTrialCriterionDictionaryRepository.Where(x => x.CriterionId == inDto.TrialCriterionId).Select(x => x.ParentCode).ToListAsync();


            var codes = criterionCodes.Select(x => x.Code).ToList();

            var dictionaryList = await _dicRepository.Where(x => codes.Contains(x.Code) && x.ParentId == null)
                .OrderBy(x => x.ShowOrder).Select(x => new GetCriterionDictionaryListOutDto()
                {
                    Code = x.Code,
                    ShowOrder = x.ShowOrder,
                    Description = x.Description
                }).ToListAsync();

            dictionaryList.ForEach(x =>
            {
                x.Count = parentCodes.Count(y => y == x.Code);
                x.Id = criterionCodes.Where(y => y.Code == x.Code).Select(x => x.Id).FirstOrDefault();
            });

            return dictionaryList;
        }

        /// <summary>
        /// 获取标准指定字典
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<Dictionary<string, List<BasicDicSelect>>> GetCriterionDictionary(GetCriterionDictionaryInDto inDto)
        {
            var searchList = await _dicRepository.Where(t => t.ParentId != null && t.IsEnable)
                .WhereIf(!inDto.DictionaryCode.IsNullOrEmpty(), x => x.Parent.Code == inDto.DictionaryCode)
                 .WhereIf(inDto.DictionaryCodeList.Count() > 0, x => inDto.DictionaryCodeList.Contains(x.Parent.Code))
                .ProjectTo<BasicDicSelect>(_mapper.ConfigurationProvider).ToListAsync();

            var result = searchList.GroupBy(t => t.ParentCode).ToDictionary(g => g.Key, g => g.OrderBy(t => t.ShowOrder).ToList());
            if (inDto.ReadingCriterionId == null)
            {
                return result;
            }
            else
            {
                List<string> selectCode = new List<string>();
                List<BasicDicSelect> criterionDictionList = new List<BasicDicSelect>();

				var isSystemCriterion = await _readingQuestionCriterionSystem.AnyAsync(x => x.Id == inDto.ReadingCriterionId);
                if (isSystemCriterion)
                {
                    selectCode = await _systemCriterionDictionaryCodeRepository.Where(x => x.SystemCriterionId == inDto.ReadingCriterionId).Select(x => x.Code).ToListAsync();

				    criterionDictionList = await _readingCriterionDictionaryRepository.Where(x => x.CriterionId == inDto.ReadingCriterionId).Select(x => new BasicDicSelect()
					{
						ChildGroup = x.Dictionary.ChildGroup,
						Code = x.Dictionary.Code,
						DataTypeEnum = x.Dictionary.DataTypeEnum,
						ParentChildCodeEnum = x.Dictionary.Parent.ChildCodeEnum,
						ShowOrder = x.Dictionary.ShowOrder,
						ParentCode = x.ParentCode,
						CrterionDictionaryGroup = x.CrterionDictionaryGroup,
						Id = x.DictionaryId,
						ParentId = x.Dictionary.ParentId,
						Value = x.Dictionary.Value,
						ValueCN = x.Dictionary.ValueCN

					}).ToListAsync();
				}
                else
                {
                    selectCode = await _trialCriterionDictionaryCodeRepository.Where(x => x.TrialCriterionId == inDto.ReadingCriterionId).Select(x => x.Code).ToListAsync();

					criterionDictionList = await _readingTrialCriterionDictionaryRepository.Where(x => x.CriterionId == inDto.ReadingCriterionId).Select(x => new BasicDicSelect()
					{
						ChildGroup = x.Dictionary.ChildGroup,
						Code = x.Dictionary.Code,
						DataTypeEnum = x.Dictionary.DataTypeEnum,
						ParentChildCodeEnum = x.Dictionary.Parent.ChildCodeEnum,
						ShowOrder = x.Dictionary.ShowOrder,
						ParentCode = x.ParentCode,
						CrterionDictionaryGroup = x.CrterionDictionaryGroup,
						Id = x.DictionaryId,
						ParentId = x.Dictionary.ParentId,
						Value = x.Dictionary.Value,
						ValueCN = x.Dictionary.ValueCN

					}).ToListAsync();
				}


                var criterionCode = await _dicRepository.Where(x => x.ConfigDictionary.Code == "Reading_eCRF_Criterion").Select(x => x.Code).ToListAsync();


                foreach (var item in criterionCode)
                {
                    if (result.ContainsKey(item))
                    {
                        result[item] = new List<BasicDicSelect>();
                    }
                }


           

                criterionDictionList = criterionDictionList.Where(x => selectCode.Contains(x.ParentCode)).ToList();

                var criterionDic = criterionDictionList.GroupBy(x => x.ParentCode).ToDictionary(g => g.Key, g => g.OrderBy(t => t.ShowOrder).ToList());

                foreach (var item in criterionDic)
                {
                    if (result.ContainsKey(item.Key))
                    {
                        result[item.Key] = item.Value;
                    }


                }

                return result;
            }

        }


        /// <summary>
        /// 获取所有下拉框 枚举  bool  数据
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<Dictionary<string, List<BasicDicSelect>>> GetBasicDataAllSelect(GetBasicDataAllSelectInDto inDto)
        {
            var searchList = await _dicRepository.Where(t => t.ParentId != null && t.IsEnable).ProjectTo<BasicDicSelect>(_mapper.ConfigurationProvider).ToListAsync();

            var result = searchList.GroupBy(t => t.ParentCode).ToDictionary(g => g.Key, g => g.OrderBy(t => t.ShowOrder).ToList());

            if (inDto.TrialReadingCriterionId == null)
            {
                return result;
            }
            else
            {
                var trialCriterionType = await _readingQuestionCriterionTrial.Where(x => x.Id == inDto.TrialReadingCriterionId).Select(x => x.CriterionType).FirstOrDefaultAsync();
                if (trialCriterionType == CriterionType.SelfDefine)
                {
                    return result;
                }


                List<string> selectCode = await _trialCriterionDictionaryCodeRepository.Where(x => x.TrialCriterionId == inDto.TrialReadingCriterionId).Select(x => x.Code).ToListAsync();


                var criterionCode = await _dicRepository.Where(x => x.ConfigDictionary.Code == "Reading_eCRF_Criterion").Select(x => x.Code).ToListAsync();


                foreach (var item in criterionCode)
                {
                    if (result.ContainsKey(item))
                    {
                        result[item] = new List<BasicDicSelect>();
                    }
                }




                var criterionDictionList = await _readingTrialCriterionDictionaryRepository.Where(x => x.CriterionId == inDto.TrialReadingCriterionId).Select(x => new BasicDicSelect()
                {
                    ChildGroup = x.Dictionary.ChildGroup,
                    Code = x.Dictionary.Code,
                    Description = x.Dictionary.Description,
                    DataTypeEnum = x.Dictionary.DataTypeEnum,
                    ParentChildCodeEnum = x.Dictionary.Parent.ChildCodeEnum,
                    ShowOrder = x.Dictionary.ShowOrder,
                    ParentCode = x.ParentCode,
                    Id = x.DictionaryId,
                    CrterionDictionaryGroup = x.CrterionDictionaryGroup,
                    ParentId = x.Dictionary.ParentId,
                    Value = x.Dictionary.Value,
                    ValueCN = x.Dictionary.ValueCN

                }).ToListAsync();

                criterionDictionList = criterionDictionList.Where(x => selectCode.Contains(x.ParentCode)).ToList();

                var criterionDic = criterionDictionList.GroupBy(x => x.ParentCode).ToDictionary(g => g.Key, g => g.OrderBy(t => t.ShowOrder).ToList());

                foreach (var item in criterionDic)
                {
                    result[item.Key] = item.Value;
                }

                return result;
            }


        }

        #region 稽查相关

        /// <summary>
        /// 获取是和否
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task<string> GetBoolValueState(bool value)
        {
            return await _dicRepository.Where(t => t.Parent.Code == "YesOrNo" && t.Code == value.ToString()).Select(x => x.ValueCN).FirstOrDefaultAsync() ?? string.Empty;
        }


        /// <summary>
        /// 获取审核状态
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="trial"></param>
        /// <param name="childCode"></param>
        /// <returns></returns>
        public async Task<string> GetAuditState<T>(Guid trial, T childCode)
        {
            var QCProcessEnum = _trialRepository.Where(x => x.Id == trial).Select(x => x.QCProcessEnum).FirstOrDefault();
            switch (QCProcessEnum)
            {


                case TrialQCProcess.SingleAudit:
                    return await _dicRepository.Where(t => t.Parent.Code == "AuditStatePE" && t.Code == Convert.ToInt32(childCode).ToString()).Select(x => x.ValueCN).FirstOrDefaultAsync() ?? string.Empty;

                case TrialQCProcess.DoubleAudit:
                    return await _dicRepository.Where(t => t.Parent.Code == "AuditStateRC" && t.Code == Convert.ToInt32(childCode).ToString()).Select(x => x.ValueCN).FirstOrDefaultAsync() ?? string.Empty;
                default:
                    return string.Empty;

            }
        }

        public async Task<string> GetBasicDataTranslateItem<T>(string parentCode, T childCode)
        {
            return await _dicRepository.Where(t => t.Parent.Code == parentCode && t.Code == Convert.ToInt32(childCode).ToString()).Select(x => x.ValueCN).FirstOrDefaultAsync() ?? string.Empty;
        }


        #endregion





    }
}
