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

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;

        public DictionaryService(IRepository<Dictionary> sysDicRepository, IRepository<DoctorDictionary> doctorDictionaryRepository, IRepository<TrialDictionary> trialDictionaryRepository,
            IRepository<Doctor> doctorRepository, IRepository<Trial> trialRepository)
        {
            _dicRepository = sysDicRepository;
            _doctorDictionaryRepository = doctorDictionaryRepository;
            _trialDictionaryRepository = trialDictionaryRepository;
            _doctorRepository = doctorRepository;
            _trialRepository = trialRepository;
        }



        /// <summary>
        /// New  查询条件   IsConfig 代表是字典类型配置项   否就是我们普通的项 和普通项的子项
        /// </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.KeyName), t => t.KeyName.Contains(basicDicQuery.KeyName!))
                .WhereIf(basicDicQuery.ConfigTypeId != null, t => t.ConfigTypeId == basicDicQuery.ConfigTypeId!)
                .WhereIf(basicDicQuery.IsConfig != null, t => t.IsConfig == basicDicQuery.IsConfig)

                .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 entity = await _dicRepository.InsertOrUpdateAsync(addOrEditBasic, true);

            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("This item is referenced by content of the reviewer's resume.");
            }

            if (await _trialDictionaryRepository.AnyAsync(t => t.DictionaryId == id) ||
                await _trialRepository.AnyAsync(t => t.ReviewModeId == id))
            {
                return ResponseOutput.NotOk("This item is referenced by content of the trial infomation.");
            }

            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





    }
}
