//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2024-07-30 10:39:09 
//     对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。
//--------------------------------------------------------------------

using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// UserFeedBackService
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Management")]
    public class UserFeedBackService(IRepository<UserFeedBack> _userFeedBackRepository,
        IRepository<VisitTask> _visitTaskRepository,
        IRepository<SubjectVisit> _subjectVisitRepository,
        IRepository<Subject> _subjectRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IUserFeedBackService
    {



        [HttpPost]
        public async Task<PageOutput<UserFeedBackView>> GetUserFeedBackList(UserFeedBackQuery inQuery)
        {

            var isCRCOrIR = _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CRA || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.IndependentReviewer;

            var userFeedBackQueryable = _userFeedBackRepository
                  .WhereIf(isCRCOrIR, t => t.CreateUserId == _userInfo.UserRoleId)
                  .WhereIf(inQuery.State != null, t => t.State == inQuery.State)
                   .WhereIf(inQuery.TrialId != null, t => t.TrialId == inQuery.TrialId)
                  .WhereIf(inQuery.QuestionType != null, t => t.QuestionType == inQuery.QuestionType)
                  .WhereIf(inQuery.BeginCreatime != null, t => t.CreateTime >= inQuery.BeginCreatime)

                  .WhereIf(inQuery.EndCreatime != null, t => t.CreateTime == inQuery.EndCreatime)
                  .WhereIf(inQuery.UserTypeEnum != null, t => t.CreateUserRole.UserTypeEnum == inQuery.UserTypeEnum)
                   .WhereIf(!string.IsNullOrEmpty(inQuery.FeedBackUserKeyInfo), t => t.CreateUserRole.FullName.Contains(inQuery.FeedBackUserKeyInfo) || t.CreateUserRole.IdentityUser.UserName.Contains(inQuery.FeedBackUserKeyInfo))
                  .WhereIf(!string.IsNullOrEmpty(inQuery.QuestionDescription), t => t.QuestionDescription.Contains(inQuery.QuestionDescription))
                  .WhereIf(!string.IsNullOrEmpty(inQuery.TrialKeyInfo), t => t.Trial.ExperimentName.Contains(inQuery.TrialKeyInfo) || t.Trial.TrialCode.Contains(inQuery.TrialKeyInfo))
                  .WhereIf(!string.IsNullOrEmpty(inQuery.SubejctAndVisitKeyInfo), t => t.Subject.Code.Contains(inQuery.SubejctAndVisitKeyInfo) || t.SubjectVisit.VisitName.Contains(inQuery.SubejctAndVisitKeyInfo))
                  .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteCode), t => t.TrialSite.TrialSiteCode.Contains(inQuery.TrialSiteCode))

                .ProjectTo<UserFeedBackView>(_mapper.ConfigurationProvider);

            var pageList = await userFeedBackQueryable.ToPagedListAsync(inQuery);

            return pageList;
        }

        [HttpPost]
        public async Task<IResponseOutput> GetUserFeedBackInfo(GetUserFeedBackQuery inQuery)
        {
            if (inQuery.Id == null && inQuery.VisitTaskId == null)
            {
                throw new BusinessValidationFailedException("Id  或者VisitTaskId 必传一个");
            }

            var result = await _userFeedBackRepository
                 .WhereIf(inQuery.Id != null, t => t.Id == inQuery.Id)
                .WhereIf(inQuery.VisitTaskId != null, t => t.VisitTaskId == inQuery.VisitTaskId)
                .ProjectTo<UserFeedBackView>(_mapper.ConfigurationProvider).FirstOrDefaultAsync();



            return ResponseOutput.Ok(result);
        }


        public async Task<IResponseOutput> AddOrUpdateUserFeedBack(UserFeedBackAddOrEdit addOrEditUserFeedBack,
            [FromServices] IMailVerificationService mailService)
        {
            addOrEditUserFeedBack.ScreenshotListStr = JsonConvert.SerializeObject(addOrEditUserFeedBack.ScreenshotList);

            if (addOrEditUserFeedBack.VisitTaskId != null)
            {
                var info = await _visitTaskRepository.Where(t => t.Id == addOrEditUserFeedBack.VisitTaskId).Select(t => new { t.SubjectId, t.SourceSubjectVisitId, t.Subject.TrialSiteId }).FirstOrDefaultAsync();

                if (info != null)
                {
                    addOrEditUserFeedBack.SubjectId = info.SubjectId;
                    addOrEditUserFeedBack.TrialSiteId = info.TrialSiteId;
                    addOrEditUserFeedBack.SubjectVisitId = info.SourceSubjectVisitId;
                }

                addOrEditUserFeedBack.State = 0;//设置解决后IR 更新反馈自动变为未解决
            }

            else if (addOrEditUserFeedBack.SubjectVisitId != null)
            {
                var info = await _subjectVisitRepository.Where(t => t.Id == addOrEditUserFeedBack.SubjectVisitId).Select(t => new { t.TrialSiteId, t.SubjectId }).FirstOrDefaultAsync();

                if (info != null)
                {
                    addOrEditUserFeedBack.TrialSiteId = info.TrialSiteId;
                    addOrEditUserFeedBack.SubjectId = info.SubjectId;
                }
            }
            else if (addOrEditUserFeedBack.SubjectId != null)
            {
                var info = await _subjectRepository.Where(t => t.Id == addOrEditUserFeedBack.SubjectId).Select(t => new { t.TrialSiteId }).FirstOrDefaultAsync();

                if (info != null)
                {
                    addOrEditUserFeedBack.TrialSiteId = info.TrialSiteId;
                }
            }



            var entity = await _userFeedBackRepository.InsertOrUpdateAsync(addOrEditUserFeedBack, true);

            //任务反馈的添加更新都需要发送邮件,其他的是添加的时候发送
            if (addOrEditUserFeedBack.VisitTaskId != null || addOrEditUserFeedBack.Id == null)
            {
                await mailService.UserFeedBackMail(entity.Id);
            }

            return ResponseOutput.Ok(entity.Id.ToString());

        }

        /// <summary>
        /// 批量更新状态
        /// </summary>
        /// <param name="batchUpdateCommand"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IResponseOutput> BatchUpdateFeedBackState(BatchUpdateCommand batchUpdateCommand)
        {
            await _userFeedBackRepository.BatchUpdateNoTrackingAsync(t => batchUpdateCommand.IdList.Contains(t.Id), u => new UserFeedBack() { State = batchUpdateCommand.State });

            return ResponseOutput.Ok();
        }


        [HttpDelete("{userFeedBackId:guid}")]
        public async Task<IResponseOutput> DeleteUserFeedBack(Guid userFeedBackId)
        {
            var success = await _userFeedBackRepository.DeleteFromQueryAsync(t => t.Id == userFeedBackId, true);
            return ResponseOutput.Ok();
        }


    }
}