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;

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

    [ApiExplorerSettings(GroupName = "Common")]
    public class DictionaryService : BaseService, IDictionaryService
    {
        private readonly IRepository<Dictionary> _dicRepository;
        private readonly IRepository<DoctorDictionary> _doctorDictionaryRepository;
        private readonly IRepository<TrialDictionary> _trialDictionaryRepository;
        private readonly IRepository<Doctor> _doctorRepository;
        private readonly IRepository<Trial> _trialRepository;
        private readonly IReadingQuestionService _readingQuestionService;

        public DictionaryService(IRepository<Dictionary> sysDicRepository, IRepository<DoctorDictionary> doctorDictionaryRepository, IRepository<TrialDictionary> trialDictionaryRepository,
            IRepository<Doctor> doctorRepository, IRepository<Trial> trialRepository,
            IReadingQuestionService readingQuestionService


            )
        {
            _dicRepository = sysDicRepository;
            _doctorDictionaryRepository = doctorDictionaryRepository;
            _trialDictionaryRepository = trialDictionaryRepository;
            _doctorRepository = doctorRepository;
            _trialRepository = trialRepository;
            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="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,
                VerifyMsg = $"已有{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;
                }
            }
            var entity = await _dicRepository.InsertOrUpdateAsync(addOrEditBasic, true, verifyExp1);
            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 _dicRepository.AnyAsync(t => t.ParentId == id))
            {
                return ResponseOutput.NotOk("有子项数据，不允许直接删除！");
            }

            if ((await _doctorDictionaryRepository.AnyAsync(t => t.DictionaryId == id)) ||
                (await _doctorRepository.AnyAsync(t => t.SpecialityId == id || t.PositionId == id || t.DepartmentId == id || t.RankId == id))

               )
            {
                return ResponseOutput.NotOk("当前条目已经在阅片人的简历中被引用。");
            }

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

            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<BasicDicSelect>>> GetBasicDataSelect(string[] searchArray)
        {

            var searchList = await _dicRepository.Where(t => searchArray.Contains(t.Parent.Code) && t.ParentId != null && t.IsEnable).ProjectTo<BasicDicSelect>(_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>
        /// 获取所有下拉框 枚举  bool  数据
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<Dictionary<string, List<BasicDicSelect>>> GetBasicDataAllSelect()
        {
            var searchList = await _dicRepository.Where(t => t.ParentId != null && t.IsEnable ).ProjectTo<BasicDicSelect>(_mapper.ConfigurationProvider).ToListAsync();

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

        #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





    }
}
