//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2021-12-23 13:20:59 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Application.Filter;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Application.Contracts;

namespace IRaCIS.Core.Application.Contracts
{
    /// <summary>
    /// TrialSiteUserSurveyService
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TrialSiteUserSurveyService : BaseService, ITrialSiteUserSurveyService
    {
        private readonly IRepository<TrialSiteUserSurvey> _trialSiteUserSurveyRepository;
        private readonly IRepository<TrialSiteSurvey> _trialSiteSurveyRepository;

        public TrialSiteUserSurveyService(IRepository<TrialSiteUserSurvey> trialSiteUserSurveyRepository, IRepository<TrialSiteSurvey> trialSiteSurveyRepository)
        {
            _trialSiteUserSurveyRepository = trialSiteUserSurveyRepository;
            _trialSiteSurveyRepository = trialSiteSurveyRepository;
        }

        [HttpPost]
        public async Task<List<TrialSiteUserSurveyView>> GetTrialSiteUserSurveyList(TrialSiteUserSurverQuery inquery)
        {

            var trialSiteUserSurveyQueryable = _trialSiteUserSurveyRepository.Where(t => t.TrialSiteSurveyId == inquery.TrialSiteSurveyId)
             .WhereIf(inquery.IsHistoryUser !=null, t => t.IsHistoryUser==inquery.IsHistoryUser)
             .ProjectTo<TrialSiteUserSurveyView>(_mapper.ConfigurationProvider, new { isEn_Us = _userInfo.IsEn_Us });

            return await trialSiteUserSurveyQueryable.ToListAsync();
        }


        [TypeFilter(typeof(TrialResourceFilter),Arguments = new object[] { "AfterStopCannNotOpt" })]
        [HttpPost("{trialId:guid}")]
        public async Task<IResponseOutput> AddOrUpdateTrialSiteUserSurvey(TrialSiteUserSurveyAddOrEdit addOrEditTrialSiteUserSurvey)
        {
          


            if (await _trialSiteSurveyRepository.AnyAsync(t => t.Id == addOrEditTrialSiteUserSurvey.TrialSiteSurveyId && (t.IsDeleted == true || t.State == TrialSiteSurveyEnum.PMCreatedAndLock), true))
            {
                //当前调研表已废除，或者调研表状态已锁定，不允许操作
                return ResponseOutput.NotOk(_localizer["TrialSiteUserSurvey_Invalid"]);
            }
      

            if (addOrEditTrialSiteUserSurvey.IsGenerateAccount  )
            {
                var trialId= _trialSiteSurveyRepository.Where(t=>t.Id == addOrEditTrialSiteUserSurvey.TrialSiteSurveyId,false,true).Select(t=>t.TrialId).FirstOrDefault();

                var trialType = _repository.Where<Trial>(t => t.Id == trialId).Select(t => t.TrialType).FirstOrDefault();

                var item = addOrEditTrialSiteUserSurvey;

                //找下系统中是否存在该用户类型的 并且邮箱 或者手机的账户
                var sysUserInfo = await _repository.Where<User>(t => t.UserTypeId == item.UserTypeId && t.EMail == item.Email).Include(t => t.UserTypeRole).FirstOrDefaultAsync();

                if (sysUserInfo != null)
                {

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

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

                        }
                    }

                    if (trialType == TrialType.NoneOfficial)
                    {

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

                        }
                    }
                }

               
            }

            var verifyExp1 = new EntityVerifyExp<TrialSiteUserSurvey>()
            {
                VerifyExp = u => u.UserTypeId == addOrEditTrialSiteUserSurvey.UserTypeId && u.Email == addOrEditTrialSiteUserSurvey.Email && u.TrialSiteSurveyId==addOrEditTrialSiteUserSurvey.TrialSiteSurveyId,
                VerifyMsg = "同一邮箱同一用户类型,生成账号的数据只允许存在一条！",
                IsVerify=addOrEditTrialSiteUserSurvey.IsGenerateAccount
                
            };

            if (addOrEditTrialSiteUserSurvey.UserTypeId != null)
            {
                var existSysUser = await _repository.Where<User>(t => t.EMail == addOrEditTrialSiteUserSurvey.Email && t.UserTypeId == addOrEditTrialSiteUserSurvey.UserTypeId).Include(d => d.UserTypeRole).FirstOrDefaultAsync();


                if (existSysUser != null)
                {
                    if (existSysUser.LastName != addOrEditTrialSiteUserSurvey.LastName || existSysUser.FirstName != addOrEditTrialSiteUserSurvey.FirstName)
                    {


                         var optEntity = await _trialSiteUserSurveyRepository.InsertOrUpdateAsync(addOrEditTrialSiteUserSurvey, true, verifyExp1);

                        //$"该用户在系统中账户名为：{existSysUser.LastName + " / " + existSysUser.FirstName} ，与填写信息存在不一致项, 现将界面信息修改为与系统一致，可进行保存"
                        return ResponseOutput.NotOk(_localizer["TrialSiteUser_InconsistentInfo", existSysUser.UserTypeRole.UserTypeShortName, existSysUser.EMail, existSysUser.LastName + " / " + existSysUser.FirstName, existSysUser.Phone],
                            new { Id= optEntity.Id,  existSysUser.LastName, existSysUser.FirstName, existSysUser.Phone, existSysUser.IsTestUser, existSysUser.IsZhiZhun }, ApiResponseCodeEnum.NeedTips);
                    }

                }
            }


            var entity = await _trialSiteUserSurveyRepository.InsertOrUpdateAsync(addOrEditTrialSiteUserSurvey, true, verifyExp1);


          

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

        }

         [TypeFilter(typeof(TrialResourceFilter),Arguments = new object[] { "AfterStopCannNotOpt" })]
        [HttpDelete("{trialSiteUserSurveyId:guid}/{trialId:guid}")]
        public async Task<IResponseOutput> DeleteTrialSiteUserSurvey(Guid trialSiteUserSurveyId)
        {          

            if (await _trialSiteUserSurveyRepository.Where(t => t.Id == trialSiteUserSurveyId).AnyAsync(t => t.TrialSiteSurvey.State == TrialSiteSurveyEnum.PMCreatedAndLock))
            {
                //---已锁定,不允许操作
                return ResponseOutput.NotOk(_localizer["TrialSiteUser_Locked"]);
            }

            var success = await _trialSiteUserSurveyRepository.BatchDeleteNoTrackingAsync(t => t.Id == trialSiteUserSurveyId);

            return ResponseOutput.Result(success);
        }






    }
}
