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

namespace IRaCIS.Core.Application.Service
{
    [ApiExplorerSettings(GroupName = "Reviewer")]
    public class DoctorListService(IRepository<Doctor> _doctorRepository,
        IRepository<Enroll> _enrollRepository,
        IRepository<EnrollDetail> _enrollDetailRepository,
        IRepository<Trial> _trialRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IDoctorListQueryService
    {


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

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

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

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


            var query = _doctorRepository.AsQueryable()
                   .WhereIf(inQuery.DepartmentId != null, t => t.DepartmentId == inQuery.DepartmentId)
                   .WhereIf(inQuery.SpecialityId != null, t => t.SpecialityId == inQuery.SpecialityId)
                   .WhereIf(inQuery.HospitalId != null, t => t.HospitalId == inQuery.HospitalId)
                   .WhereIf(inQuery.PositionId != null, t => t.PositionId == inQuery.PositionId)
                   .WhereIf(inQuery.RankId != null, t => t.RankId == inQuery.RankId)
                   .WhereIf(inQuery.ContractorStatus != null, t => t.CooperateStatus == inQuery.ContractorStatus)
                   .WhereIf(inQuery.InformationConfirmed != null, t => t.ResumeStatus == inQuery.InformationConfirmed)
                   .WhereIf(inQuery.AcceptingNewTrial != null, t => t.AcceptingNewTrial == inQuery.AcceptingNewTrial)
                   .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Name), t => t.ChineseName.Contains(inQuery.Name) || (t.LastName + t.FirstName).Contains(inQuery.Name))
                   .WhereIf(inQuery.Nation != null, t => t.Nation == inQuery.Nation)
                   .WhereIf(evaluationCriteriaCount > 0, t => t.TrialExperienceCriteriaList.Count(t => inQuery.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(inQuery.EnrollStatus != null && inQuery.EnrollStatus == (int)ReviewerEnrollStatus.Yes, t => t.EnrollList.Any(u => u.EnrollStatus == EnrollStatus.DoctorReading))

                   .ProjectTo<DoctorDTO>(_mapper.ConfigurationProvider);

            return await query.ToPagedListAsync(inQuery, nameof(DoctorDTO.CreateTime));


        }


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

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

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

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

            var query = _doctorRepository/*.WhereIf(nation != AttendedReviewerType.USAndCN,  t => t.Nation ==(int) nation)*/

             .WhereIf(inQuery.DepartmentId != null, t => t.DepartmentId == inQuery.DepartmentId)
             .WhereIf(inQuery.SpecialityId != null, t => t.SpecialityId == inQuery.SpecialityId)
             .WhereIf(trialConfig.TrialType == TrialType.NoneOfficial, t => t.IsVirtual == true)
             .WhereIf(trialConfig.TrialType != TrialType.NoneOfficial, t => t.IsVirtual == false)
             .WhereIf(inQuery.HospitalId != null, t => t.HospitalId == inQuery.HospitalId)
             .WhereIf(inQuery.PositionId != null, t => t.PositionId == inQuery.PositionId)
             .WhereIf(inQuery.RankId != null, t => t.RankId == inQuery.RankId)
             .WhereIf(inQuery.ContractorStatus != null, t => t.CooperateStatus == inQuery.ContractorStatus)
             .WhereIf(inQuery.InformationConfirmed != null, t => t.ResumeStatus == inQuery.InformationConfirmed)
             .WhereIf(inQuery.AcceptingNewTrial != null, t => t.AcceptingNewTrial == inQuery.AcceptingNewTrial)
             .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Name), t => t.ChineseName.Contains(inQuery.Name) || (t.LastName + t.FirstName).Contains(inQuery.Name))
             .WhereIf(evaluationCriteriaCount > 0, t => t.TrialExperienceCriteriaList.Count(t => inQuery.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(inQuery.EnrollStatus != null && inQuery.EnrollStatus == (int)ReviewerEnrollStatus.Yes, t => t.EnrollList.Any(u => u.EnrollStatus == EnrollStatus.DoctorReading))

             .ProjectTo<SelectionReviewerDTO>(_mapper.ConfigurationProvider);

            var result = await query.ToPagedListAsync(inQuery);

            //是否已申请   申请时间 申请人
            var doctorStateList = await _enrollDetailRepository.Where(x => x.TrialId == inQuery.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 inQuery)
        {

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

            var doctorPageList = await doctorQuery.ToPagedListAsync(inQuery);


            var enrollStateList = await _enrollDetailRepository.Where(x => x.TrialId == inQuery.TrialId)
                   //提交CRO  以及下载简历列表  
                   .WhereIf(inQuery.IntoGroupSearchState == 1, t => t.EnrollStatus == EnrollStatus.HasCommittedToCRO)
                   //CRO确认列表  状态为 已提交CRO
                   .WhereIf(inQuery.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 = inQuery.IntoGroupSearchState == 1 ? (int)EnrollStatus.HasCommittedToCRO : (int)EnrollStatus.InviteIntoGroup;
                    u.OptTime = opt.OptTime;
                    u.OptUserName = opt.OptUserName;
                }
                else
                {
                    u.DoctorTrialState = inQuery.IntoGroupSearchState == 1 ? (int)EnrollStatus.HasDownloadResume : (int)EnrollStatus.HasCommittedToCRO;
                }
            });

            if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM)
            {
                //SPM 要看到提交的时间 提交人
                var enrollCommitList = await _enrollDetailRepository.Where(x => x.TrialId == inQuery.TrialId)
                     //提交CRO  以及下载简历列表  
                     .WhereIf(inQuery.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 = _enrollRepository(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 _enrollDetailRepository.Where(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 inQuery)
        {


            var doctorQuery = _enrollRepository.Where(x => x.TrialId == inQuery.TrialId && x.EnrollStatus >= EnrollStatus.InviteIntoGroup)
               .ProjectTo<ConfirmationReviewerDTO>(_mapper.ConfigurationProvider);

            var doctorPageList = await doctorQuery.ToPagedListAsync(inQuery);

            var enrollStateList = await _enrollDetailRepository.Where(x => x.TrialId == inQuery.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




    }
}

