//--------------------------------------------------------------------
//     此代码由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;

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

        public TrialSiteUserSurveyService(IRepository<TrialSiteUserSurvey> trialSiteUserSurveyRepository)
        {
            _trialSiteUserSurveyRepository = trialSiteUserSurveyRepository;
        }

        [HttpGet("{trialSiteSurveyId:guid}")]
        public async Task<List<TrialSiteUserSurveyView>> GetTrialSiteUserSurveyList(Guid trialSiteSurveyId)
        {

            var trialSiteUserSurveyQueryable = _trialSiteUserSurveyRepository.Where(t => t.TrialSiteSurveyId == trialSiteSurveyId)
             //.WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.SPM, t => t.TrialSiteSurvey.State >= TrialSiteSurveyEnum.CRCSubmitted)
             //.WhereIf(_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM|| _userInfo.UserTypeEnumInt == (int)UserTypeEnum.CPM, t => t.TrialSiteSurvey.State >= TrialSiteSurveyEnum.SPMApproved)
             .ProjectTo<TrialSiteUserSurveyView>(_mapper.ConfigurationProvider);

            return await trialSiteUserSurveyQueryable.ToListAsync();
        }

         [TypeFilter(typeof(TrialResourceFilter),Arguments = new object[] { "AfterStopCannNotOpt" })]
        [HttpPost("{trialId:guid}")]
        public async Task<IResponseOutput> AddOrUpdateTrialSiteUserSurvey(TrialSiteUserSurveyAddOrEdit addOrEditTrialSiteUserSurvey)
        {
          
            if (await _trialSiteUserSurveyRepository.Where(t => t.Id == addOrEditTrialSiteUserSurvey.Id).AnyAsync(t => t.TrialSiteSurvey.State == TrialSiteSurveyEnum.PMCreatedAndLock))
            {
                return ResponseOutput.NotOk("已锁定,不允许操作");
            }

            if (addOrEditTrialSiteUserSurvey.UserTypeId != null && ( _userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM))
            {
                var existSysUser = await _repository.FirstOrDefaultAsync<User>(t => t.EMail == addOrEditTrialSiteUserSurvey.Email && t.UserTypeId == addOrEditTrialSiteUserSurvey.UserTypeId);


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

                }

            }


            if (addOrEditTrialSiteUserSurvey.IsGenerateAccount  )
            {
                var trialId= _trialSiteUserSurveyRepository.Where(t=>t.TrialSiteSurveyId == addOrEditTrialSiteUserSurvey.TrialSiteSurveyId).Select(t=>t.TrialSiteSurvey.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("正式类型 、培训类型的项目 不允许加入测试用户 ");

                        }
                    }

                    if (trialType == TrialType.NoneOfficial)
                    {

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

                        }
                    }
                }

               
            }

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

            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("已锁定,不允许操作");
            }

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

            return ResponseOutput.Result(success);
        }






    }
}
