//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2022-03-24 13:22:54 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------

using IRaCIS.Core.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore;
using Microsoft.AspNetCore.Authorization;
using Panda.DynamicWebApi.Attributes;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// TrialUserPreparation Service
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TrialUserPreparationService : BaseService, ITrialUserPreparationService
    {
        private readonly IRepository<TrialUserPreparation> _trialUserPreparationRepository;
        private readonly IRepository<TrialExternalUser> _trialExternalUseRepository;
        private readonly IRepository<User> _userRepository;
        private readonly IRepository<TrialUser> _trialUserRepository;
        private readonly IRepository<TrialSiteUserSurvey> _trialSiteUserSurveyRepository;
        private readonly IRepository<TrialSiteUser> _trialSiteUseRepository;

        public TrialUserPreparationService(IRepository<TrialUserPreparation> trialUserPreparationRepository,
            IRepository<TrialExternalUser> trialExternalUseRepository,
            IRepository<User> userRepository, IRepository<TrialUser> trialUserRepository, IRepository<TrialSiteUserSurvey> trialSiteUserSurveyRepository, IRepository<TrialSiteUser> trialSiteUseRepository)
        {
            _trialUserPreparationRepository = trialUserPreparationRepository;
            _trialExternalUseRepository = trialExternalUseRepository;
            _userRepository = userRepository;
            _trialUserRepository = trialUserRepository;
            _trialSiteUserSurveyRepository = trialSiteUserSurveyRepository;
            _trialSiteUseRepository = trialSiteUseRepository;
        }

        /// <summary>
        ///  项目下  人员邀请 加入列表
        /// </summary>
        /// <param name="queryTrialUserPreparation"></param>
        /// <returns></returns>
        public async Task<List<TrialUserPreparationView>> GetTrialUserPreparationList(TrialUserPreparationQuery queryTrialUserPreparation)
        {


            var trialUserPreparationQueryable = _trialUserPreparationRepository
                .WhereIf(queryTrialUserPreparation.UserTypeId != null, t => t.User.UserTypeId == queryTrialUserPreparation.UserTypeId)
                .ProjectTo<TrialUserPreparationView>(_mapper.ConfigurationProvider);

            return await trialUserPreparationQueryable.ToListAsync();
        }


        /// <summary>
        ///  不带Token访问  加入项目 记录 同意与否
        /// </summary>
        /// <param name="joinCommand"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task JoinTrial(JoinCommand joinCommand)
        {


            await UserJoinTrialAsync(joinCommand.TrialUserInfo);
        }





     




        /// <summary>
        /// 用户加入项目
        /// </summary>
        /// <param name="joinTrialCommand"></param>
        /// <returns></returns>
        [NonDynamicMethod]
        public async Task<IResponseOutput> UserJoinTrialAsync(UserJoinTrialCommand joinTrialCommand)
        {
            var trialId = joinTrialCommand.TrialId;
            var userId = joinTrialCommand.UserId;

            if (joinTrialCommand.IsExternal)
            {

                //判断TrialUser中是否存在  不存在就插入
                if (!await _trialUserRepository.AnyAsync(t => t.TrialId == trialId && t.UserId == userId))
                {

                    await _trialUserRepository.AddAsync(new TrialUser() { TrialId = trialId, UserId = userId });


                    await _trialExternalUseRepository.BatchUpdateNoTrackingAsync(t => t.TrialId == trialId && t.SystemUserId == userId,
                        u => new TrialExternalUser() { InviteState = TrialExternalUserStateEnum.UserConfirmed });


                    await _userRepository.SaveChangesAsync();
                }
            }
            else
            {
                if (joinTrialCommand.SiteId == null)
                {
                    return ResponseOutput.NotOk("传参有误,  SiteId必传");
                }

                if (!_trialUserRepository.Where(t => t.TrialId == trialId && t.UserId == userId).Any())
                {
                    await _trialUserRepository.AddAsync(new TrialUser() { TrialId = trialId, UserId = userId });

                    await _trialSiteUseRepository.AddAsync(new TrialSiteUser() { TrialId = trialId, SiteId =(Guid) joinTrialCommand.SiteId, UserId = userId });
                }
            }

            await _userRepository.BatchUpdateNoTrackingAsync(t => t.Id == userId, u => new User() { Status = UserStateEnum.Enable });


            return ResponseOutput.Ok();

        }




    }
}
