using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Service.Inspection.DTO;
using IRaCIS.Core.Application.Service.Inspection.Interface;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using Panda.DynamicWebApi.Attributes;


namespace IRaCIS.Core.Application.Service.Inspection
{
    [NonDynamicWebApi]
    public class InspectionService(IRepository<DataInspection> _dataInspectionRepository,
        IRepository<Dictionary> _dictionaryRepository,
        IRepository<TrialSign> _trialSignRepository,
        IRepository<User> _userRepository,
        IRepository<TrialSite> _trialSiteRepository,
        IRepository<Trial> _trialRepository,
        IRepository<Subject> _subjectRepository,
        IRepository<SubjectVisit> _subjectVisitRepository,
        IRepository<UserType> _userTypeRepository,
        IRepository<VisitTask> _visitTaskRepository,
        IRepository<FrontAuditConfig> _frontAuditConfigRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IInspectionService
    {




        public async Task<PageOutput<GetDataInspectionOutDto>> GetInspectionList(GetDataInspectionDto inQuery)
        {
            //_repository.GetQueryable.GetQueryable < DataInspection >

            var trialData = await _trialRepository.Where(x => x.Id == inQuery.TrialId).AsNoTracking().FirstNotNullAsync();


            trialData.TrialFinishTime = trialData.TrialFinishTime == null ? DateTime.Now : trialData.TrialFinishTime;

            #region 逻辑代码
            var query = from data in _dataInspectionRepository.Where()
                            //.Where(x => (x.TrialId == dto.TrialId)||(x.TrialId==null&&x.CreateTime>= trialData.CreateTime && x.CreateTime <= trialData.TrialFinishTime))


                        join trial in _trialRepository.Where().IgnoreQueryFilters() on data.TrialId equals trial.Id into trialtemp
                        from leftrial in trialtemp.DefaultIfEmpty()


                        join trialSite in _trialSiteRepository.Where().IgnoreQueryFilters() on data.TrialSiteId equals trialSite.Id into trialSitetemp
                        from lefttrialSite in trialSitetemp.DefaultIfEmpty()


                        join subject in _subjectRepository.Where().IgnoreQueryFilters() on data.SubjectId equals subject.Id into subtemp
                        from leftsubject in subtemp.DefaultIfEmpty()
                        join subjectVisit in _subjectVisitRepository.Where().IgnoreQueryFilters() on data.SubjectVisitId equals subjectVisit.Id into subjectVisittemp
                        from leftsubjectVisit in subjectVisittemp.DefaultIfEmpty()
                        join parent in _dataInspectionRepository.Where() on data.ParentId equals parent.Id into parenttemp
                        from leftparent in parenttemp.DefaultIfEmpty()
                        join user in _userRepository.Where().IgnoreQueryFilters() on data.CreateUserId equals user.Id into usertemp
                        from leftuser in usertemp.DefaultIfEmpty()
                        join usertype in _userTypeRepository.Where().IgnoreQueryFilters() on leftuser.UserTypeId equals usertype.Id into usertypetemp
                        from leftusertype in usertypetemp.DefaultIfEmpty()

                        join visttask in _visitTaskRepository.Where().IgnoreQueryFilters() on data.VisitTaskId equals visttask.Id into visttasktemp
                        from leftvisttask in visttasktemp.DefaultIfEmpty()

                            //join trialCriterion in _repository.GetQueryable<ReadingQuestionCriterionTrial>().IgnoreQueryFilters() on data.TrialReadingCriterionId equals trialCriterion.Id into criterion
                            //from leftCriterion in criterion.DefaultIfEmpty()

                            //join moduleTyped in _dictionaryRepository.Where().Where(x => x.Code == "ModuleType") on 1 equals 1
                            //join moduleTypec in _dictionaryRepository.Where() on new { ParentId = moduleTyped.Id, ModuleType = data.ModuleType } equals new { ParentId = moduleTypec.ParentId.Value, ModuleType = moduleTypec.Value } into moduleTypectemp

                            //join childrenTyped in _dictionaryRepository.Where().Where(x => x.Code == "ChildrenType") on 1 equals 1
                            //join childrenTypec in _dictionaryRepository.Where() on new { ParentId = childrenTyped.Id, ModuleType = data.ChildrenType } equals new { ParentId = childrenTypec.ParentId.Value, ModuleType = childrenTypec.Value } into childrenTypectemp
                            //from leftchildrenTypec in childrenTypectemp.DefaultIfEmpty()

                            //join ObjectTyped in _dictionaryRepository.Where().Where(x => x.Code == "ObjectType") on 1 equals 1
                            //join ObjectTypec in _dictionaryRepository.Where() on new { ParentId = ObjectTyped.Id, ModuleType = data.ObjectType } equals new { ParentId = ObjectTypec.ParentId.Value, ModuleType = ObjectTypec.Value } into objectTypetemp
                            //from leftObjectType in objectTypetemp.DefaultIfEmpty()

                            //join OptTyped in _dictionaryRepository.Where().Where(x => x.Code == "OptType") on 1 equals 1
                            //join OptTypec in _dictionaryRepository.Where() on new { ParentId = OptTyped.Id, ModuleType = data.OptType } equals new { ParentId = OptTypec.ParentId.Value, ModuleType = OptTypec.Value } into optTypetemp
                            //from leftOptType in optTypetemp.DefaultIfEmpty()


                        join trialSign in _trialSignRepository.Where().IgnoreQueryFilters() on data.SignId equals trialSign.Id into trialSigntemp
                        from lefttrialSign in trialSigntemp.DefaultIfEmpty()
                        join leftfrontAuditConfig in _frontAuditConfigRepository.Where().Where(x => x.ConfigType == "M" && x.Identification != null && x.IsEnable == true) on
                            data.Identification.ToLower()
                         equals
                            leftfrontAuditConfig.Identification.ToLower()
                        join moduleTypec in _dictionaryRepository.Where() on new { ModuleType = leftfrontAuditConfig.ModuleTypeId!.Value } equals new { ModuleType = moduleTypec.Id } into moduleTypectemp
                        from leftmoduleTypec in moduleTypectemp.DefaultIfEmpty()
                        join OptTypec in _dictionaryRepository.Where() on new { ModuleType = leftfrontAuditConfig.OptTypeId!.Value } equals new { ModuleType = OptTypec.Id } into optTypetemp
                        from leftOptType in optTypetemp.DefaultIfEmpty()

                        select new GetDataInspectionOutDto()
                        {
                            CreateTime = data.CreateTime,
                            CreateUserId = data.CreateUserId,
                            ModuleTypeId = leftmoduleTypec.Id,
                            BlindName = data.VisitTask.TaskBlindName,
                            TaskName = data.VisitTask.TaskName,
                            TrialId = data.TrialId,
                            TrialSiteId = data.TrialSiteId,
                            SubjectId = data.SubjectId,
                            SubjectVisitId = data.SubjectVisitId,
                            //OptType = data.OptType,
                            IP = data.IP,
                            Reason = data.Reason,
                            IsSign = leftfrontAuditConfig.IsHaveSign,
                            SignId = data.SignId,
                            ParentId = data.ParentId,
                            ChildrenTypeId = data.ChildrenTypeId,
                            //JsonDetail = data.JsonDetail,
                            //SiteName = data.SiteName,
                            //ExperimentName = data.TrialName,
                            //FirstName = leftsubject.FirstName,
                            //LastName = leftsubject.LastName,

                            Id = data.Id,
                            //ParentJson = leftparent.JsonDetail,
                            VisitName = leftsubjectVisit.VisitName,
                            SubjectVisitName = leftsubjectVisit.VisitName,


                            //CreateUserName = leftuser.UserName,
                            //RoleName = leftusertype.UserTypeShortName,

                            CreateUserRealName = data.CreateUserRealName,
                            CreateUserName = data.CreateUserName,
                            RoleName = data.RoleName,


                            //UserFirstName = leftuser.FirstName,
                            //UserLastName = leftuser.LastName,
                            ExperimentName = leftrial.ExperimentName,

                            //SubjectCode = leftvisttask.BlindSubjectCode.IsNullOrEmpty()? leftsubject.Code: leftvisttask.BlindSubjectCode,
                            SubjectCode = leftvisttask.IsAnalysisCreate ? leftvisttask.BlindSubjectCode : leftsubject.Code,
                            SiteCode = lefttrialSite.TrialSiteCode,

                            ResearchProgramNo = leftrial.ResearchProgramNo,
                            ObjectTypeId = data.ObjectTypeId,
                            Description = leftfrontAuditConfig.Description,
                            DescriptionCN = leftfrontAuditConfig.DescriptionCN,

                            ModuleTypeName = leftmoduleTypec.Value,
                            ModuleTypeNameCN = leftmoduleTypec.ValueCN,

                            SignText = lefttrialSign.SignText,
                            Identification = leftfrontAuditConfig.Identification,
                            FrontAuditConfigId = leftfrontAuditConfig.Id,
                            ParentIdentification = leftparent.Identification,
                            OptTypeId = leftOptType.Id,
                            VisitNum = leftsubjectVisit.VisitNum,
                            InPlan = leftsubjectVisit.InPlan,
                            //IsFrontAdd=data.IsFrontAdd,
                            BatchId = data.BatchId,
                            OptType = leftOptType.Value,
                            OptTypeCN = leftOptType.ValueCN,
                            ObjectRelationParentId = data.ObjectRelationParentId,
                            GeneralId = data.GeneralId,

                            TrialReadingCriterionId = data.TrialReadingCriterionId,
                            TrialReadingCriterionName = data.TrialReadingCriterion.CriterionName
                        };

            query = query.WhereIf(inQuery.TrialSiteId != null, x => x.TrialSiteId == inQuery.TrialSiteId)
                    //.Where(x => (x.TrialId == dto.TrialId) || (x.TrialId == null && x.CreateTime >= trialData.CreateTime && x.CreateTime <= trialData.TrialFinishTime))
                    .Where(x => x.TrialId == inQuery.TrialId)

            #region 废弃
                   //   .WhereIf(dto.BatchId != null && dto.ObjectRelationParentId == null && dto.GeneralId == null, x => x.BatchId == dto.BatchId)
                   //  .WhereIf(dto.BatchId != null && dto.GeneralId != null && dto.ObjectRelationParentId == null, x => x.BatchId == dto.BatchId ||
                   //  ((x.GeneralId == dto.GeneralId || x.ObjectRelationParentId == dto.GeneralId) && x.CreateTime <= dto.RelationDeadlineTime.Value.AddSeconds(1)))
                   //  .WhereIf(dto.ObjectRelationParentId != null && dto.BatchId != null && dto.GeneralId != null,
                   //  x =>
                   //  x.BatchId == dto.BatchId ||      //同一事务批次
                   //  //x.ObjectRelationParentId == dto.ObjectRelationParentId || //不同对象 但是同一层级 适用于子对象


                   //((x.GeneralId == dto.ObjectRelationParentId || //子稽查 查询父记录
                   //  x.GeneralId == dto.GeneralId ||  //同一对象
                   //  x.ObjectRelationParentId == dto.GeneralId  //父稽查 查询子记录
                   //  ) && x.CreateTime <= dto.RelationDeadlineTime.Value.AddSeconds(1)))
            #endregion
                   .WhereIf(inQuery.BatchId != null, x => x.BatchId == inQuery.BatchId)
                   .WhereIf(inQuery.BatchId == null && inQuery.GeneralId != null, x => x.GeneralId == inQuery.GeneralId)
                   .WhereIf(inQuery.TrialReadingCriterionId != null, x => x.TrialReadingCriterionId == inQuery.TrialReadingCriterionId)


                   .WhereIf(!inQuery.TaskName.IsNullOrEmpty(), x => x.TaskName.Contains(inQuery.TaskName) || x.BlindName.Contains(inQuery.TaskName))
                 .WhereIf(!inQuery.SubjectInfo.IsNullOrEmpty(), x => x.SubjectCode.Contains(inQuery.SubjectInfo))
                 .WhereIf(!inQuery.RoleName.IsNullOrEmpty(), x => x.RoleName.Contains(inQuery.RoleName))
                 //.WhereIf(dto.VisitPlanInfo != null&& dto.VisitPlanInfo!=(decimal) 1.11, x => x.VisitNum == dto.VisitPlanInfo)
                 //.WhereIf(dto.VisitPlanInfo != (decimal)1.11,x=>x.InPlan!=null&& x.InPlan==false)
                 .WhereIf(inQuery.StartTime != null, x => x.CreateTime >= inQuery.StartTime)
                 .WhereIf(inQuery.EndTime != null, x => x.CreateTime <= inQuery.EndTime)
                 .WhereIf(inQuery.ModuleType != null, x => x.ModuleTypeId == inQuery.ModuleType)
                 .WhereIf(!inQuery.Description.IsNullOrEmpty(), x => x.Description.Contains(inQuery.Description) || x.DescriptionCN.Contains(inQuery.Description))
                 .WhereIf(!inQuery.OpByUserName.IsNullOrEmpty(), x => x.CreateUserName.Contains(inQuery.OpByUserName))
                  .WhereIf(!inQuery.CreateUserName.IsNullOrEmpty(), x => x.CreateUserName.Contains(inQuery.CreateUserName) || x.CreateUserRealName.Contains(inQuery.CreateUserName))

                 //.WhereIf(!dto.SubjectInfo.IsNullOrEmpty(), x => x.SubjectCode.Contains(dto.SubjectInfo))
                 .WhereIf(inQuery.IsSign != null, x => x.IsSign == inQuery.IsSign);
            #endregion

            if (inQuery.VisitPlanInfo != null && inQuery.VisitPlanInfo.Value != (decimal)1.11)
            {
                query = query.Where(x => x.VisitNum == inQuery.VisitPlanInfo.Value);
            }
            else if (inQuery.VisitPlanInfo != null)
            {
                query = query.Where(x => x.InPlan == false);
            }
            return await query.ToPagedListAsync(inQuery, nameof(GetDataInspectionOutDto.CreateTime));
        }




        /// <summary>
        /// 传入参数记录ID
        /// </summary>
        /// <param name="SignInfo"></param>
        /// <returns></returns>
        public async Task<Guid> RecordSing(SignDTO SignInfo)
        {
            if (SignInfo != null)
            {
                var verifyResult = await VerifySignatureAsync(SignInfo);
                var signId = await AddSignRecordAsync(SignInfo);
                _userInfo.SignId = signId;
                return signId;
            }
            else
            {
                return default(Guid);
            }

        }

        /// <summary>
        /// 完成签名
        /// </summary>
        /// <param name="signId"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        public async Task CompletedSign(Guid signId, IResponseOutput response)
        {
            if (response.IsSuccess)
            {
                await _trialSignRepository.BatchUpdateNoTrackingAsync(t => t.Id == signId, u => new TrialSign() { IsCompleted = true });
            }
        }



        /// <summary> 验证用户签名信息 </summary> ///  
        public async Task<IResponseOutput> VerifySignatureAsync(SignDTO signDTO)
        {
            var user = await _userRepository.FirstOrDefaultAsync(u => u.UserName == signDTO.UserName && u.Password == signDTO.PassWord);
            if (user == null)
            {
                throw new BusinessValidationFailedException(_localizer["User_CheckNameOrPw"]);
            }
            else if (user.Status == UserStateEnum.Disable)
            {
                //---当前用户已被禁用。
                throw new BusinessValidationFailedException(_localizer["Inspection_UserDisabled"]);
            }
            return ResponseOutput.Ok();

        }

        /// <summary> 添加签名记录 </summary> ///  
        public async Task<Guid> AddSignRecordAsync(SignDTO signDTO)
        {
            var add = await _trialSignRepository.AddAsync(_mapper.Map<TrialSign>(signDTO));

            var success = await _trialSignRepository.SaveChangesAsync();

            return add.Id;

        }


    }
}
