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

namespace IRaCIS.Core.Application.Service
{
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TrialMaintenanceService(IRepository<TrialUser> _trialUseRepository,
        IRepository<User> _userRepository,
        IRepository<TrialSiteUser> _trialSiteUserRepository,
        IRepository<SubjectVisit> _subjectVisitRepository,
        IRepository<Trial> _trialRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, ITrialMaintenanceService
    {

        [HttpGet]
        public async Task<List<TrialUserBasicInfo>> GetTrialUserList(Guid trialId)
        {
            return await _trialUseRepository.Where(t => t.TrialId == trialId, ignoreQueryFilters: true)
                  .Select(t => new TrialUserBasicInfo() { FullName = t.User.FullName, UserId = t.UserId, UserTypeId = t.User.UserTypeId, UserName = t.User.UserName })
                  .ToListAsync();
        }

        /// <summary>
        /// Setting页面    获取项目参与人员列表
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<TrialMaintenanceDTO>> GetMaintenanceUserList(TrialMaintenanceQuery inQuery)
        {

            var query = _trialUseRepository.Where(t => t.TrialId == inQuery.TrialId).IgnoreQueryFilters()
                .WhereIf(inQuery.UserTypeId != null, t => t.User.UserTypeId == inQuery.UserTypeId)
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.UserName), t => t.User.UserName.Contains(inQuery.UserName))

                 .WhereIf(inQuery.IsDeleted != null, t => t.IsDeleted == inQuery.IsDeleted)
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.OrganizationName), t => t.User.OrganizationName.Contains(inQuery.OrganizationName))
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.UserRealName), t => (t.User.FullName).Contains(inQuery.UserRealName))
                .ProjectTo<TrialMaintenanceDTO>(_mapper.ConfigurationProvider);

            return await query.ToPagedListAsync(inQuery, nameof(TrialMaintenanceDTO.UpdateTime));

        }





        /// <summary> Setting页面  为 site 勾选CRC用户列表</summary> 
        [HttpPost]
        public async Task<PageOutput<AssginSiteCRCListDTO>> GetSiteCRCScreeningList(SiteCRCQuery inQuery)
        {
            // 最开始过滤site已经选择的用户 现在又改回去。。。 

            var query = _trialUseRepository.Where(t => t.TrialId == inQuery.TrialId).IgnoreQueryFilters()
                .Where(t => t.User.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator || t.User.UserTypeEnum == UserTypeEnum.CRA)
                 .WhereIf(inQuery.UserTypeId != null, t => t.User.UserTypeId == inQuery.UserTypeId)
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.UserRealName), t => (t.User.FullName).Contains(inQuery.UserRealName))
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.OrganizationName), t => t.User.OrganizationName.Contains(inQuery.OrganizationName))
                .ProjectTo<AssginSiteCRCListDTO>(_mapper.ConfigurationProvider, new { trialSiteId = inQuery.TrialSiteId });

            return await query.ToPagedListAsync(inQuery);

        }


        /// <summary> Setting页面   项目参与人员勾选列表   </summary>
        [HttpPost]
        public async Task<PageOutput<TrialUserScreeningDTO>> GetTrialUserScreeningList(TrialUserQuery inQuery)
        {
            var trialType = _trialRepository.Where(t => t.Id == inQuery.TrialId).Select(t => t.TrialType).FirstOrDefault();

            var userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.ClinicalResearchCoordinator, UserTypeEnum.CRA, UserTypeEnum.IQC, UserTypeEnum.APM, UserTypeEnum.MIM, UserTypeEnum.QA, UserTypeEnum.MW, UserTypeEnum.MC };

            //if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.SuperAdmin)
            {
                userTypeEnums.Add(UserTypeEnum.ProjectManager);
            }


            //之前已经选择的用户 不放在列表中，现在又要改回去 废弃
            var query = _userRepository.Where(t => t.UserTypeEnum != UserTypeEnum.SuperAdmin)

                 //正式或者培训的项目  不能允许测试用户（必须正式用户）  同时必须是内部的用户
                 .WhereIf(trialType == TrialType.OfficialTrial || trialType == TrialType.Training, t => t.IsTestUser == false && t.IsZhiZhun)

                 //测试项目 可以加入 测试用户  或者内部正式用户
                 .WhereIf(trialType == TrialType.NoneOfficial, t => t.IsTestUser == true || (t.IsTestUser == false && t.IsZhiZhun))


                 .Where(t => userTypeEnums.Contains(t.UserTypeEnum))


                 .WhereIf(!string.IsNullOrWhiteSpace(inQuery.UserRealName), t => (t.FullName).Contains(inQuery.UserRealName))
                 .WhereIf(!string.IsNullOrWhiteSpace(inQuery.UserName), t => t.UserName.Contains(inQuery.UserName))
                 .WhereIf(!string.IsNullOrWhiteSpace(inQuery.OrganizationName), t => t.OrganizationName.Contains(inQuery.OrganizationName))
                 .WhereIf(inQuery.UserTypeEnum != null, t => t.UserTypeEnum == inQuery.UserTypeEnum)
                 //.WhereIf(_userInfo.IsAdmin, t => t.UserTypeRole.Type == UserTypeGroup.TrialUser)
                 //.WhereIf(!_userInfo.IsAdmin, t => t.UserTypeRole.Type == UserTypeGroup.TrialUser || t.UserTypeEnum != UserTypeEnum.ProjectManager)
                 .ProjectTo<TrialUserScreeningDTO>(_mapper.ConfigurationProvider, new { trialId = inQuery.TrialId });

            return await query.ToPagedListAsync(inQuery);

        }


        /// <summary>
        /// Setting页面   批量添加项目参与人员
        /// </summary>
        /// <param name="userTrialCommands"></param>
        /// <returns></returns>
        //[TrialAudit(AuditType.TrialAudit, AuditOptType.AddTrialStaff)]
        [HttpPost]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
        //[Authorize(Policy = IRaCISPolicy.PM_APM)]
        public async Task<IResponseOutput> AddTrialUsers(TrialUserAddCommand[] userTrialCommands)
        {

            var addArray = _mapper.Map<TrialUser[]>(userTrialCommands);

            var trialUsers = await _trialUseRepository.AddRangeAsync(addArray);

            foreach (var item in trialUsers)
            {
                item.JoinTime = DateTime.Now;
            }


            var success = await _trialUseRepository.SaveChangesAsync();

            return ResponseOutput.Result(success);
        }



        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
        //[Authorize(Policy = IRaCISPolicy.PM_APM)]
        [HttpPut]
        public async Task<IResponseOutput> UpdateTrialUser(UpdateTrialUserCommand updateTrialUserCommand)
        {
            var trialUser = await _trialUseRepository.Where(t => t.Id == updateTrialUserCommand.Id, true, true).FirstOrDefaultAsync();

            if (trialUser == null) return Null404NotFound(trialUser);


            if (updateTrialUserCommand.IsDeleted)
            {
                if (await _trialSiteUserRepository.AnyAsync(t => t.UserId == trialUser.UserId && t.TrialId == trialUser.TrialId))
                {
                    // ----人员已加入现场维护
                    return ResponseOutput.NotOk(_localizer["TrialMaint_PersonnelJoined"]);
                }

                if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.IQC)
                {
                    await _subjectVisitRepository.BatchUpdateNoTrackingAsync(t => t.CurrentActionUserId == trialUser.UserId && t.TrialId == trialUser.TrialId && t.IsTake, u => new SubjectVisit() { CurrentActionUserId = null, CurrentActionUserExpireTime = null, IsTake = false });
                }

            }

            _mapper.Map(updateTrialUserCommand, trialUser);

            await _trialUseRepository.SaveChangesAsync();

            return ResponseOutput.Ok();


        }


        /// <summary> 项目参与人员退出   其中IQC退出 回去释放工作量 </summary>
        //[TrialAudit(AuditType.TrialAudit, AuditOptType.DeleteTrailStaff)]
        [HttpDelete, Route("{id:guid}/{trialId:guid}/{isDelete:bool}")]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
        [UnitOfWork]
        [Obsolete]
        public async Task<IResponseOutput> DeleteMaintenanceUser(Guid id, bool isDelete)
        {

            var trialUser = await _trialUseRepository.AsQueryable().IgnoreQueryFilters().FirstOrDefaultAsync(t => t.Id == id);

            if (trialUser == null) return Null404NotFound(trialUser);

            if (await _trialSiteUserRepository.AnyAsync(t => t.UserId == trialUser.UserId && t.TrialId == trialUser.TrialId))
            {
                //---人员已加入现场维护
                return ResponseOutput.NotOk(_localizer["TrialMaint_PersonnelJoined"]);
            }

            if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.IQC && isDelete)
            {
                await _subjectVisitRepository.BatchUpdateNoTrackingAsync(t => t.CurrentActionUserId == trialUser.UserId && t.TrialId == trialUser.TrialId && t.IsTake, u => new SubjectVisit() { CurrentActionUserId = null, CurrentActionUserExpireTime = null, IsTake = false });
            }

            await _trialUseRepository.BatchUpdateNoTrackingAsync(t => t.Id == id, u => new TrialUser() { IsDeleted = isDelete, RemoveTime = isDelete ? DateTime.Now : null });

            await _trialUseRepository.SaveChangesAsync();

            return ResponseOutput.Ok();
        }



    }
}
