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

using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Domain.Share;
using MimeKit;
using MailKit.Security;
using Microsoft.AspNetCore.Authorization;
using Panda.DynamicWebApi.Attributes;
using IRaCIS.Core.Application.Auth;
using IRaCIS.Application.Services;
using IRaCIS.Core.Application.Filter;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 项目外部人员  录入流程相关
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TrialExternalUserService : BaseService, ITrialExternalUserService
    {
        private readonly IRepository<TrialExternalUser> _trialExternalUseRepository;
        private readonly IRepository<User> _userRepository;
        private readonly IRepository<TrialUser> _trialUserRepository;
        private readonly IRepository<TrialSiteUserSurvey> _trialSiteSurveyUserRepository;
        private readonly IRepository<TrialSiteUser> _trialSiteUserRepository;
        private readonly IMailVerificationService _mailVerificationService;

        public TrialExternalUserService(IRepository<TrialExternalUser> trialExternalUseRepository, IRepository<User> userRepository, IRepository<TrialUser> trialUserRepository,
            IRepository<TrialSiteUserSurvey> trialSiteSurveyUserRepository, IRepository<TrialSiteUser> trialSiteUserRepository,
          IMailVerificationService mailVerificationService)
        {
            _trialExternalUseRepository = trialExternalUseRepository;
            _userRepository = userRepository;
            _trialUserRepository = trialUserRepository;
            _trialSiteSurveyUserRepository = trialSiteSurveyUserRepository;
            _trialSiteUserRepository = trialSiteUserRepository;

            _mailVerificationService = mailVerificationService;
        }



        [HttpPost]
        public async Task<List<TrialExternalUserView>> GetTrialExternalUserList(TrialExternalUserQuery queryTrialExternalUser)
        {

            var trialExternalUserQueryable = _trialExternalUseRepository.Where(t => t.TrialId == queryTrialExternalUser.TrialId)
                .WhereIf(!string.IsNullOrEmpty(queryTrialExternalUser.Phone), t => t.Phone.Contains(queryTrialExternalUser.Phone))
                .WhereIf(!string.IsNullOrEmpty(queryTrialExternalUser.Email), t => t.Email.Contains(queryTrialExternalUser.Email))
                .WhereIf(!string.IsNullOrEmpty(queryTrialExternalUser.Name), t => (t.LastName + " / " + t.FirstName).Contains(queryTrialExternalUser.Name))
            .ProjectTo<TrialExternalUserView>(_mapper.ConfigurationProvider);

            return await trialExternalUserQueryable.ToListAsync();
        }



        /// <summary>
        /// 添加和更新接口   已验证邮箱和账户类型不允许添加重复项
        /// </summary>
        /// <param name="addOrEditTrialExternalUser"></param>
        /// <returns></returns>
        //[Authorize(Policy = IRaCISPolicy.PM_APM)]
        [UnitOfWork]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
        public async Task<IResponseOutput> AddOrUpdateTrialExternalUser(TrialExternalUserAddAndSendEmail addOrEditTrialExternalUser)
        {

            if (addOrEditTrialExternalUser.Id == null)
            {
                var existSysUser = await _userRepository.FirstOrDefaultAsync(t => t.EMail == addOrEditTrialExternalUser.Email && t.UserTypeId == addOrEditTrialExternalUser.UserTypeId);

                if (existSysUser != null)
                {
                    if (existSysUser.LastName != addOrEditTrialExternalUser.LastName || existSysUser.FirstName != addOrEditTrialExternalUser.FirstName)
                    {
                        //$"该用户在系统中的用户名为：{existSysUser.LastName + " / " + existSysUser.FirstName} 电话：{existSysUser.Phone}，与填写信息存在不一致项, 请将界面信息修改为与系统一致，再进行保存",
                        return ResponseOutput.NotOk(_localizer["TrialExternalUser_Inconsistency", existSysUser.LastName + " / " + existSysUser.FirstName, existSysUser.Phone], new { existSysUser.LastName, existSysUser.FirstName, existSysUser.Phone, existSysUser.IsZhiZhun, existSysUser.IsTestUser }, ApiResponseCodeEnum.NeedTips);
                    }

                }

                //处理  生成账户

                if (await _trialExternalUseRepository.AnyAsync(t =>
                        t.Email == addOrEditTrialExternalUser.Email &&
                        t.UserTypeId == addOrEditTrialExternalUser.UserTypeId && t.TrialId == addOrEditTrialExternalUser.TrialId))
                {
                //---系统已经存在与列表中填写的邮箱和用户类型相同的账户，请确认。
                    return ResponseOutput.NotOk(_localizer["TrialExternalUser_EmailTypeDuplicate"]);
                }



                var addEntity = _mapper.Map<TrialExternalUser>(addOrEditTrialExternalUser);

                await _trialExternalUseRepository.AddAsync(addEntity);


                var existUser = await _userRepository.FirstOrDefaultAsync(t => t.EMail == addOrEditTrialExternalUser.Email && t.UserTypeId == addOrEditTrialExternalUser.UserTypeId);
                var trialType = await _repository.Where<Trial>(t => t.Id == addOrEditTrialExternalUser.TrialId).Select(t => t.TrialType).FirstOrDefaultAsync();

                if (existUser != null)
                {
                    addEntity.IsSystemUser = true;
                    addEntity.SystemUserId = existUser.Id;

                }
                else
                {

                    //生成账户  并插入

                    var generateUser = _mapper.Map<User>(addOrEditTrialExternalUser);

                    if (trialType == TrialType.NoneOfficial)
                    {
                        generateUser.IsTestUser = true;                   
                    }

                    // 外部人员生成账号 都是外部的
                    generateUser.IsZhiZhun = false;

                    generateUser.Code = _userRepository.Select(t => t.Code).DefaultIfEmpty().Max() + 1;


                    generateUser.UserCode = AppSettings.GetCodeStr(generateUser.Code, nameof(User));

                    generateUser.UserName = generateUser.UserCode;

                    generateUser.UserTypeEnum = _repository.Where<UserType>(t => t.Id == generateUser.UserTypeId).Select(t => t.UserTypeEnum).First();

                    generateUser.Password = MD5Helper.Md5("123456");

                    generateUser.Status = UserStateEnum.Disable;

                    var newAddUser = await _repository.AddAsync(generateUser);


                    addEntity.IsSystemUser = false;
                    addEntity.SystemUserId = newAddUser.Id;


                    existUser = newAddUser;

                }

                #region 验证用户 能否加入

                if (trialType == TrialType.OfficialTrial || trialType == TrialType.Training)
                {

                    if (existUser.IsTestUser)
                    {
                //---正式类型 、培训类型的项目 不允许加入测试用户 
                        throw new BusinessValidationFailedException(_localizer["TrialExternalUser_TestUserNotAllowed"]);

                    }
                }

                if (trialType == TrialType.NoneOfficial)
                {

                    if (existUser.IsTestUser == false )
                    {
                //---测试项目  不允许加入正式用户 
                        throw new BusinessValidationFailedException(_localizer["TrialExternalUser_FormalUserNotAllowed"]);
                    }
                }

                #endregion


                await _trialExternalUseRepository.SaveChangesAsync();


                //添加的时候就发邮件  现在省略
                if (addOrEditTrialExternalUser.IsSendEmail)
                {
                    await SendExternalUserJoinEmail(new TrialExternalUserSendEmail()
                    {
                        BaseUrl = addOrEditTrialExternalUser.BaseUrl,
                        RouteUrl = addOrEditTrialExternalUser.RouteUrl,
                        TrialId = addOrEditTrialExternalUser.TrialId,
                        SendUsers = new List<UserEmail>()
                        {
                            new UserEmail()
                            {
                                Id = addEntity.Id,
                                Email=addEntity.Email,
                                IsSystemUser=addEntity.IsSystemUser,
                                SystemUserId=addEntity.SystemUserId
                            }
                        }
                    });
                }


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

            }
            else
            {
                //---人员信息不支持编辑，请删除后重新添加。
                return ResponseOutput.NotOk(_localizer["TrialExternalUser_NotEditable"]);

            }
        }




        [HttpDelete("{trialExternalUserId:guid}/{isSystemUser:bool}/{systemUserId}")]
        //[Authorize(Policy = IRaCISPolicy.PM_APM)]
        public async Task<IResponseOutput> DeleteTrialExternalUser(Guid trialExternalUserId, bool isSystemUser, Guid systemUserId)
        {
            var trialExternalUser = await _trialExternalUseRepository.FirstOrDefaultAsync(t => t.Id == trialExternalUserId);

            if (await _trialUserRepository.AnyAsync(t => t.TrialId == trialExternalUser.TrialId && t.UserId == trialExternalUser.SystemUserId))
            {
                //---当前用户已参与到项目，不允许删除
                return ResponseOutput.NotOk(_localizer["TrialExternalUser_CannotDelete"]);
            }


            var success = await _trialExternalUseRepository.BatchDeleteNoTrackingAsync(t => t.Id == trialExternalUserId);

            if (isSystemUser == false)
            {
                await _userRepository.BatchDeleteNoTrackingAsync(t => t.Id == systemUserId);
            }

            return ResponseOutput.Result(success);
        }


        //New  省掉邀请流程
        [HttpPost]
        //[Authorize(Policy = IRaCISPolicy.PM_APM)]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
        [UnitOfWork]
        public async Task<IResponseOutput> SendExternalUserJoinEmail(TrialExternalUserSendEmail sendEmail)
        {
            var trialId = sendEmail.TrialId;

            foreach (var userInfo in sendEmail.SendUsers)
            {
                var userId = userInfo.SystemUserId;




                //判断TrialUser中是否存在  不存在就插入  注意退出了，也不能再加进来
                if (!await _trialUserRepository.AnyAsync(t => t.TrialId == trialId && t.UserId == userId, true))
                {

                    await _repository.AddAsync(new TrialUser() { TrialId = trialId, UserId = userId, JoinTime = DateTime.Now });

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

                    await _trialExternalUseRepository.BatchUpdateNoTrackingAsync(t => t.Id == userInfo.Id, u => new TrialExternalUser() { IsJoin = true });


                    await _userRepository.SaveChangesAsync();
                }

                await _mailVerificationService.ExternalUserJoinEmail(trialId, userId, sendEmail.BaseUrl, sendEmail.RouteUrl);

            }

            return ResponseOutput.Ok();

        }



    }
}
