using IRaCIS.Application.Interfaces;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Domain.Share;
using System.Linq.Dynamic.Core;
using IRaCIS.Core.Infra.EFCore;
using Microsoft.AspNetCore.Mvc;

namespace IRaCIS.Application.Services
{
    [ApiExplorerSettings(GroupName = "Reviewer")]
    public class DoctorListService : BaseService, IDoctorListQueryService
    {
        private readonly IRepository<Doctor> _doctorRepository;

        public DoctorListService(IRepository<Doctor> doctorRepository)
        {
            _doctorRepository = doctorRepository;
        }

        /// <summary>
        /// Reviewer列表分页查询
        /// </summary>       
        [HttpPost]
        public async Task<PageOutput<DoctorDTO>> GetDoctorSearchList(DoctorSearchDTO doctorSearch)
        {

            // 项目经验 多选
            var evaluationCriteriaCount = doctorSearch.EvaluationCriteriaIdList.Count();

            //  搜索条件 ReadingType 、Subspeciality、Title  多选
            var count = doctorSearch.ReadingTypeIdList.Count + doctorSearch.TitleIdList.Count + doctorSearch.SubspecialityIdList.Count;

            var guidList = doctorSearch.ReadingTypeIdList.Concat(doctorSearch.SubspecialityIdList).Concat(doctorSearch.TitleIdList);


            var query = _doctorRepository.AsQueryable()
                   .WhereIf(doctorSearch.DepartmentId != null, t => t.DepartmentId == doctorSearch.DepartmentId)
                   .WhereIf(doctorSearch.SpecialityId != null, t => t.SpecialityId == doctorSearch.SpecialityId)
                   .WhereIf(doctorSearch.HospitalId != null, t => t.HospitalId == doctorSearch.HospitalId)
                   .WhereIf(doctorSearch.PositionId != null, t => t.PositionId == doctorSearch.PositionId)
                   .WhereIf(doctorSearch.RankId != null, t => t.RankId == doctorSearch.RankId)
                   .WhereIf(doctorSearch.ContractorStatus != null, t => t.CooperateStatus == doctorSearch.ContractorStatus)
                   .WhereIf(doctorSearch.InformationConfirmed != null, t => t.ResumeStatus == doctorSearch.InformationConfirmed)
                   .WhereIf(doctorSearch.AcceptingNewTrial != null, t => t.AcceptingNewTrial == doctorSearch.AcceptingNewTrial)
                   .WhereIf(!string.IsNullOrWhiteSpace(doctorSearch.Name), t => t.ChineseName.Contains(doctorSearch.Name) || (t.LastName + t.FirstName).Contains(doctorSearch.Name))
                   .WhereIf(doctorSearch.Nation != null, t => t.Nation == doctorSearch.Nation)
                   .WhereIf(evaluationCriteriaCount > 0, t => t.TrialExperienceCriteriaList.Count(t => doctorSearch.EvaluationCriteriaIdList.Contains(t.EvaluationCriteriaId)) == evaluationCriteriaCount)
                   ////用户类型  看到简历的范围这里需要确认  
                   //.WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ReviewerCoordinator, t => t.UserList.Any(u => u.UserId == _userInfo.Id))
                   .WhereIf(count > 0, t => t.DoctorDicRelationList.Count(u => guidList.Contains(u.DictionaryId)) == count)
                   .WhereIf(doctorSearch.EnrollStatus != null && doctorSearch.EnrollStatus == (int)ReviewerEnrollStatus.Yes, t => t.EnrollList.Any(u => u.EnrollStatus == EnrollStatus.DoctorReading))

                   .ProjectTo<DoctorDTO>(_mapper.ConfigurationProvider);

            return await query.ToPagedListAsync(doctorSearch.PageIndex, doctorSearch.PageSize, doctorSearch.SortField == string.Empty ? "CreateTime" : doctorSearch.SortField, doctorSearch.Asc);


        }


        #region 入组查询相关
        /// <summary>
        /// 获取可筛选筛选及已经筛选的医生列表
        /// </summary>
        [HttpPost]
        public async Task<PageOutput<SelectionReviewerDTO>> GetSelectionReviewerList(
            ReviewerSelectionQueryDTO selectionQuery)
        {
            //项目配置需要的医生过滤  2表示混合
            var trialConfig = await _repository.Where<Trial>(s => s.Id == selectionQuery.TrialId).Select(t=>new { t.AttendedReviewerType ,t.TrialType} ).FirstOrDefaultAsync().IfNullThrowException();

            var nation = trialConfig.AttendedReviewerType;
            // 临床项目经验 多选
            var evaluationCriteriaCount = selectionQuery.EvaluationCriteriaIdList.Count();

            //  搜索条件 ReadingType 、Subspeciality、Title  多选
            var count = selectionQuery.ReadingTypeIdList.Count + selectionQuery.TitleIdList.Count + selectionQuery.SubspecialityIdList.Count;

            var guidList = selectionQuery.ReadingTypeIdList.Concat(selectionQuery.SubspecialityIdList).Concat(selectionQuery.TitleIdList);

            var query = _doctorRepository.WhereIf(nation != AttendedReviewerType.USAndCN,  t => t.Nation ==(int) nation)
             .WhereIf(selectionQuery.DepartmentId != null, t => t.DepartmentId == selectionQuery.DepartmentId)
             .WhereIf(selectionQuery.SpecialityId != null, t => t.SpecialityId == selectionQuery.SpecialityId)
             .WhereIf(trialConfig.TrialType == TrialType.NoneOfficial, t => t.IsVirtual ==true)
             .WhereIf(trialConfig.TrialType != TrialType.NoneOfficial, t => t.IsVirtual == false)
             .WhereIf(selectionQuery.HospitalId != null, t => t.HospitalId == selectionQuery.HospitalId)
             .WhereIf(selectionQuery.PositionId != null, t => t.PositionId == selectionQuery.PositionId)
             .WhereIf(selectionQuery.RankId != null, t => t.RankId == selectionQuery.RankId)
             .WhereIf(selectionQuery.ContractorStatus != null, t => t.CooperateStatus == selectionQuery.ContractorStatus )
             .WhereIf(selectionQuery.InformationConfirmed != null, t => t.ResumeStatus == selectionQuery.InformationConfirmed)
             .WhereIf(selectionQuery.AcceptingNewTrial != null, t => t.AcceptingNewTrial == selectionQuery.AcceptingNewTrial)
             .WhereIf(!string.IsNullOrWhiteSpace(selectionQuery.Name), t => t.ChineseName.Contains(selectionQuery.Name) || (t.LastName + t.FirstName).Contains(selectionQuery.Name))
             .WhereIf(evaluationCriteriaCount > 0, t => t.TrialExperienceCriteriaList.Count(t => selectionQuery.EvaluationCriteriaIdList.Contains(t.EvaluationCriteriaId)) == evaluationCriteriaCount)
             //用户类型  看到简历的范围这里需要确认  
             .WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ReviewerCoordinator, t => t.UserList.Any(u => u.UserId == _userInfo.Id))
             .WhereIf(count > 0, t => t.DoctorDicRelationList.Count(u => guidList.Contains(u.DictionaryId)) == count)
             .WhereIf(selectionQuery.EnrollStatus != null && selectionQuery.EnrollStatus == (int)ReviewerEnrollStatus.Yes, t => t.EnrollList.Any(u => u.EnrollStatus == EnrollStatus.DoctorReading))

             .ProjectTo<SelectionReviewerDTO>(_mapper.ConfigurationProvider);

            var result = await query.ToPagedListAsync(selectionQuery.PageIndex, selectionQuery.PageSize, selectionQuery.SortField == string.Empty ? "ReviewerCode" : selectionQuery.SortField, selectionQuery.Asc);

            //是否已申请   申请时间 申请人
            var doctorStateList =  await _repository.Where<EnrollDetail>(x => x.TrialId == selectionQuery.TrialId && x.EnrollStatus == EnrollStatus.HasApplyDownloadResume)
               .ProjectTo<DoctorStateModelDTO>(_mapper.ConfigurationProvider).ToListAsync();

            result.CurrentPageData.ToList().ForEach(doctor =>
              {
                  //简历申请列表  --处理已经申请的
                  var doctorState = doctorStateList.FirstOrDefault(t => t.DoctorId == doctor.Id && t.IntoGroupState == (int)EnrollStatus.HasApplyDownloadResume);
                  if (doctorState != null)
                  {
                      doctor.DoctorTrialState = (int)EnrollStatus.HasApplyDownloadResume;
                      doctor.OptTime = doctorState.OptTime;
                      doctor.OptUserName = doctorState.OptUserName;
                  }
              });

            return result;


        }

        /// <summary>
        /// 获取提交CRO或者CRO审核的Reviewer列表
        /// </summary>
        /// <summary>
        /// 根据状态获取医生列表，入组 相关接口  （提交CRO-1） CRO确认-4  
        /// </summary>
        [HttpPost]
        public async Task<PageOutput<ConfirmationReviewerDTO>> GetSubmissionOrApprovalReviewerList(
            ReviewerSubmissionQueryDTO param)
        {

            var doctorQuery = _repository.Where<Enroll>(x => x.TrialId == param.TrialId)
                  //提交CRO  以及下载简历列表  
                  .WhereIf(param.IntoGroupSearchState == 1, t => t.EnrollStatus >= EnrollStatus.HasApplyDownloadResume)
                  //CRO确认列表  状态为 已提交CRO
                  .WhereIf(param.IntoGroupSearchState == 4, t => t.EnrollStatus >= EnrollStatus.HasCommittedToCRO)
                  .ProjectTo<ConfirmationReviewerDTO>(_mapper.ConfigurationProvider);

            var doctorPageList = await doctorQuery.ToPagedListAsync(param.PageIndex, param.PageSize, param.SortField == "" ? "Code" : param.SortField, param.Asc);


            var enrollStateList = await _repository.Where<EnrollDetail>(x => x.TrialId == param.TrialId)
                   //提交CRO  以及下载简历列表  
                   .WhereIf(param.IntoGroupSearchState == 1, t => t.EnrollStatus == EnrollStatus.HasCommittedToCRO)
                   //CRO确认列表  状态为 已提交CRO
                   .WhereIf(param.IntoGroupSearchState == 4, t => t.EnrollStatus == EnrollStatus.InviteIntoGroup)
                   .ProjectTo<DoctorStateModelDTO>(_mapper.ConfigurationProvider).ToListAsync();


         

            doctorPageList.CurrentPageData.ToList().ForEach(u =>
            {
                var opt = enrollStateList.FirstOrDefault(t => t.DoctorId == u.Id);
                if (opt != null)
                {
                    u.DoctorTrialState = param.IntoGroupSearchState == 1 ? (int)EnrollStatus.HasCommittedToCRO : (int)EnrollStatus.InviteIntoGroup;
                    u.OptTime = opt.OptTime;
                    u.OptUserName = opt.OptUserName;
                }
            });

            if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM)
            {
                //SPM 要看到提交的时间 提交人
                var enrollCommitList = await _repository.Where<EnrollDetail>(x => x.TrialId == param.TrialId)
                     //提交CRO  以及下载简历列表  
                     .WhereIf(param.IntoGroupSearchState == 4, t => t.EnrollStatus == EnrollStatus.HasCommittedToCRO)
                     .ProjectTo<DoctorStateModelDTO>(_mapper.ConfigurationProvider).ToListAsync();


                doctorPageList.CurrentPageData.ToList().ForEach(u =>
                {
                    var opt = enrollCommitList.FirstOrDefault(t => t.DoctorId == u.Id);
                    if (opt != null)
                    {
                       
                        u.SubmmitTime = opt.OptTime;
                        u.SubmmitUserName = opt.OptUserName;
                    }
                });

            }

            return doctorPageList;



        }


        //public async  Task<PageOutput<ConfirmationReviewerDTO>> GetSPMSubmissionOrApprovalReviewerList(
        //    ReviewerSubmissionQueryDTO param)
        //{
        //    var doctorQuery = _repository.Where<Enroll>(x => x.TrialId == param.TrialId)
        //          //提交CRO  以及下载简历列表  
        //          .WhereIf(param.IntoGroupSearchState == 1, t => t.EnrollStatus >= (int)EnrollStatus.HasApplyDownloadResume)
        //          //CRO确认列表  状态为 已提交CRO
        //          .WhereIf(param.IntoGroupSearchState == 4, t => t.EnrollStatus >= (int)EnrollStatus.HasCommittedToCRO)
        //          .ProjectTo<ConfirmationReviewerDTO>(_mapper.ConfigurationProvider);

        //    var doctorPageList = await doctorQuery.ToPagedListAsync(param.PageIndex, param.PageSize, param.SortField == "" ? "Code" : param.SortField, param.Asc);


        //    var enrollStateList = await _repository.Where<EnrollDetail>(x => x.TrialId == param.TrialId)
        //           //提交CRO  以及下载简历列表  
        //           .WhereIf(param.IntoGroupSearchState == 1, t => t.EnrollStatus == (int)EnrollStatus.HasCommittedToCRO)
        //           //CRO确认列表  状态为 已提交CRO
        //           .WhereIf(param.IntoGroupSearchState == 4, t => t.EnrollStatus == (int)EnrollStatus.InviteIntoGroup)
        //           .ProjectTo<DoctorStateModelDTO>(_mapper.ConfigurationProvider).ToListAsync();


        //    doctorPageList.CurrentPageData.ToList().ForEach(u =>
        //    {
        //        var opt = enrollStateList.FirstOrDefault(t => t.DoctorId == u.Id);
        //        if (opt != null)
        //        {
        //            u.DoctorTrialState = param.IntoGroupSearchState == 1 ? (int)EnrollStatus.HasCommittedToCRO : (int)EnrollStatus.InviteIntoGroup;
        //            u.OptTime = opt.OptTime;
        //            u.OptUserName = opt.OptUserName;
        //        }
        //    });

        //    return doctorPageList;
        //}

        /// <summary>
        /// 获取项目下医生入组状态列表[Confirmation]
        /// </summary>
        [HttpPost]
        public async Task<PageOutput<ConfirmationReviewerDTO>> GetConfirmationReviewerList(
            ReviewerConfirmationQueryDTO param)
        {


            var doctorQuery =  _repository.Where<Enroll>(x => x.TrialId == param.TrialId && x.EnrollStatus >= EnrollStatus.InviteIntoGroup)
               .ProjectTo<ConfirmationReviewerDTO>(_mapper.ConfigurationProvider);

            var doctorPageList = await doctorQuery.ToPagedListAsync(param.PageIndex, param.PageSize, param.SortField == "" ? "Code" : param.SortField, param.Asc);

            var enrollStateList = await _repository.Where<EnrollDetail>(x => x.TrialId == param.TrialId && x.EnrollStatus > EnrollStatus.InviteIntoGroup)
                 .ProjectTo<DoctorStateModelDTO>(_mapper.ConfigurationProvider).ToListAsync();



            doctorPageList.CurrentPageData.ToList().ForEach(u =>
            {
                u.DoctorTrialState = (int)EnrollStatus.InviteIntoGroup;
                var opt = enrollStateList.FirstOrDefault(t => t.DoctorId == u.Id);
                if (opt != null)
                {
                    u.DoctorTrialState = opt.IntoGroupState;
                    u.OptTime = opt.OptTime;
                    u.OptUserName = opt.OptUserName;
                }
            });

            return doctorPageList;

        }



        #endregion




    }
}

