using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using Microsoft.Extensions.Localization;
using System.Linq.Expressions;

namespace IRaCIS.Core.Application.Service
{
    public  class QCCommon: BaseService
    {

    

        /// <summary>
        /// 验证CRC 是否已提交 已提交 就不允许进行任何操作，如果是IQC 那么还验证是否是当前任务领取人
        /// </summary>
        /// <param name="_repository"></param>
        /// <param name="_userInfo"></param>
        /// <param name="subjectVisitId"></param>
        /// <returns></returns>
        /// <exception cref="BusinessValidationFailedException"></exception>
        public  async Task VerifyIsCRCSubmmitAsync(IRepository _repository, IUserInfo _userInfo, Guid? subjectVisitId = null)
        {
            if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator)
            {
                //添加的时候不验证
                if (subjectVisitId != null)
                {
                    if (await _repository.AnyAsync<SubjectVisit>(t => t.Id == subjectVisitId && t.SubmitState == SubmitStateEnum.Submitted &&
                              (!t.QCChallengeList.Any(u => u.ReuploadEnum == QCChanllengeReuploadEnum.QCAgreeUpload))))
                    {
                       //---CRC 已提交影像，不能进行操作。
                        throw new BusinessValidationFailedException(_localizer["QCCommon_CannotOperate"]);
                    }
                }
            }


            //IQC 的时候 验证是不是当前领取人
            if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.IQC)
            {

                await VerifyIsCanQCAsync(_repository, _userInfo, null, subjectVisitId);

            }

        }

        public  async Task VerifyIsCanQCAsync(IRepository _repository, IUserInfo _userInfo, SubjectVisit? subjectVisit = null, Guid? subjectVisitId = null)
        {
            if (subjectVisitId != null)
            {
                subjectVisit = (await _repository.FirstOrDefaultAsync<SubjectVisit>(t => t.Id == subjectVisitId)).IfNullThrowException();
            }
            if (subjectVisit!.CurrentActionUserId != _userInfo.Id)
            {
                //---您不是该质控任务当前领取人，没有操作权限!
                throw new BusinessValidationFailedException(_localizer["QCCommon_NoPermission"]);
            }
        }



        public  async Task VerifyStudyImageDataAsync(IRepository _repository, Guid subjectId, Guid subjectVisitId, DateTime imageDate)
        {
            var visitList = await _repository.Where<SubjectVisit>(t => t.SubjectId == subjectId).Select(t => new { t.VisitNum, t.EarliestScanDate, t.LatestScanDate, t.Id }).ToListAsync();

            var currentVisitNum = await _repository.Where<SubjectVisit>(t => t.Id == subjectVisitId).Select(t => t.VisitNum).FirstOrDefaultAsync();



            //小于当前访视 最近的最晚拍片
            var before = visitList.Where(u => u.VisitNum < currentVisitNum).Max(k => k.LatestScanDate);

            if (before != null && before > imageDate)
            {
                //当前访视检查时间{imageDate.ToString("yyyy-MM-dd")}不能早于前序访视检查时间{before?.ToString("yyyy-MM-dd")}，请核对检查数据是否有误
                throw new BusinessValidationFailedException(_localizer["QCCommon_CheckTimeEarly", imageDate.ToString("yyyy-MM-dd"), before?.ToString("yyyy-MM-dd")]);
            }


            //大于当前访视 最近的最早拍片日期  
            var after = visitList.Where(u => u.VisitNum > currentVisitNum).Min(k => k.EarliestScanDate);

            if (after != null && after < imageDate)
            {
                //$"当前访视检查时间{imageDate.ToString("yyyy-MM-dd")}不能晚于该访视之后的检查时间{after?.ToString("yyyy-MM-dd")}，请核对检查数据是否有误"
                throw new BusinessValidationFailedException(_localizer["QCCommon_CheckTimeLate", imageDate.ToString("yyyy-MM-dd"), after?.ToString("yyyy-MM-dd")]);

            }
        }



        #region 处理方式多选过滤条件

        public static Expression<Func<SubjectVisit, bool>> GetSubjectVisitFilter(string[]? VisitPlanArray)
        {
            Expression<Func<SubjectVisit, bool>> svExpression = x => true;

            bool isNeedVisitSearch = VisitPlanArray != null && VisitPlanArray?.Length > 0;

            if (isNeedVisitSearch)
            {
                var inPlanArray = VisitPlanArray!.Where(t => !t.Contains('.')).Select(t => decimal.Parse(t)).ToArray();
                var isSelectOutPlan = VisitPlanArray!.Any(t => t.Contains('.'));


                if (inPlanArray.Length > 0)
                {
                    svExpression = svExpression.And(t => inPlanArray.Contains(t.VisitNum));

                    if (isSelectOutPlan)
                    {
                        svExpression = svExpression.Or(t => t.InPlan == false);

                    }
                }
                else if (isSelectOutPlan)
                {
                    svExpression = t => t.InPlan == false;
                }




            }

            return svExpression;
        }


        public static Expression<Func<QCChallenge, bool>> GetQCChallengeFilter(string[]? VisitPlanArray)
        {
            Expression<Func<QCChallenge, bool>> svExpression = x => true;

            bool isNeedVisitSearch = VisitPlanArray != null && VisitPlanArray?.Length > 0;

            if (isNeedVisitSearch)
            {
                var inPlanArray = VisitPlanArray!.Where(t => !t.Contains('.')).Select(t => decimal.Parse(t)).ToArray();
                var isSelectOutPlan = VisitPlanArray!.Any(t => t.Contains('.'));


                if (inPlanArray.Length > 0)
                {
                    svExpression = svExpression.And(t => inPlanArray.Contains(t.SubjectVisit.VisitNum));

                    if (isSelectOutPlan)
                    {
                        svExpression = svExpression.Or(t => t.SubjectVisit.InPlan == false);

                    }
                }
                else if (isSelectOutPlan)
                {
                    svExpression = t => t.SubjectVisit.InPlan == false;
                }



            }

            return svExpression;
        }


        public static Expression<Func<DicomStudy, bool>> GetDicomStudySubjectVisitFilter(string[]? VisitPlanArray)
        {
            Expression<Func<DicomStudy, bool>> svExpression = x => true;

            bool isNeedVisitSearch = VisitPlanArray != null && VisitPlanArray?.Length > 0;

            if (isNeedVisitSearch)
            {
                var inPlanArray = VisitPlanArray!.Where(t => !t.Contains('.')).Select(t => decimal.Parse(t)).ToArray();
                var isSelectOutPlan = VisitPlanArray!.Any(t => t.Contains('.'));


                if (inPlanArray.Length > 0)
                {
                    svExpression = svExpression.And(t => inPlanArray.Contains(t.SubjectVisit.VisitNum));

                    if (isSelectOutPlan)
                    {
                        svExpression = svExpression.Or(t => t.SubjectVisit.InPlan == false);

                    }
                }
                else if (isSelectOutPlan)
                {
                    svExpression = t => t.SubjectVisit.InPlan == false;
                }




            }

            return svExpression;
        }


        public static Expression<Func<NoneDicomStudy, bool>> GetNoneDicomStudySubjectVisitFilter(string[]? VisitPlanArray)
        {
            Expression<Func<NoneDicomStudy, bool>> svExpression = x => true;

            bool isNeedVisitSearch = VisitPlanArray != null && VisitPlanArray?.Length > 0;

            if (isNeedVisitSearch)
            {
                var inPlanArray = VisitPlanArray!.Where(t => !t.Contains('.')).Select(t => decimal.Parse(t)).ToArray();
                var isSelectOutPlan = VisitPlanArray!.Any(t => t.Contains('.'));


                if (inPlanArray.Length > 0)
                {
                    svExpression = svExpression.And(t => inPlanArray.Contains(t.SubjectVisit.VisitNum));

                    if (isSelectOutPlan)
                    {
                        svExpression = svExpression.Or(t => t.SubjectVisit.InPlan == false);

                    }
                }
                else if (isSelectOutPlan)
                {
                    svExpression = t => t.SubjectVisit.InPlan == false;
                }




            }

            return svExpression;
        }

        public static Expression<Func<StudyMonitor, bool>> GetStudyMonitorSubjectVisitFilter(string[]? VisitPlanArray)
        {
            Expression<Func<StudyMonitor, bool>> svExpression = x => true;

            bool isNeedVisitSearch = VisitPlanArray != null && VisitPlanArray?.Length > 0;

            if (isNeedVisitSearch)
            {
                var inPlanArray = VisitPlanArray!.Where(t => !t.Contains('.')).Select(t => decimal.Parse(t)).ToArray();
                var isSelectOutPlan = VisitPlanArray!.Any(t => t.Contains('.'));


                if (inPlanArray.Length > 0)
                {
                    svExpression = svExpression.And(t => inPlanArray.Contains(t.SubjectVisit.VisitNum));

                    if (isSelectOutPlan)
                    {
                        svExpression = svExpression.Or(t => t.SubjectVisit.InPlan == false);

                    }
                }

                else if (isSelectOutPlan)
                {
                    svExpression = t => t.SubjectVisit.InPlan == false;
                }



            }

            return svExpression;
        }

        #endregion
    }
}
