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

namespace IRaCIS.Core.Application.Contracts
{
    /// <summary>
    /// UserTypeRoleService 
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Management")]
    public class UserTypeRoleService : BaseService, IUserTypeService
    {
        private readonly IRepository<UserType> _userTypeRepository;

        public UserTypeRoleService(IRepository<UserType> userTypeRepository)
        {
            _userTypeRepository = userTypeRepository;
        }

        [HttpPost]
        public async Task<List<UserTypeRoleView>> GetUserTypeRoleList(UserTypeQuery userTypeQuery)
        {

            var userTypeRoleQueryable = _userTypeRepository
                .WhereIf(!string.IsNullOrWhiteSpace(userTypeQuery.SearchFilter), t => t.Description.Contains(userTypeQuery.SearchFilter!) || t.UserTypeName.Contains(userTypeQuery.SearchFilter!) || t.UserTypeShortName.Contains(userTypeQuery.SearchFilter!))

                .WhereIf(userTypeQuery.GroupId!=null,t=>t.UserTypeGroupList.Any(t=>t.DictionaryId== userTypeQuery.GroupId))
                .OrderBy(t => t.UserTypeEnum).ProjectTo<UserTypeRoleView>(_mapper.ConfigurationProvider);

            return await userTypeRoleQueryable.ToListAsync();
        }



        public async Task<IResponseOutput> AddOrUpdateUserTypeRole(UserTypeMenuAddOrEdit addOrEditUserTypeRole)
        {

            var verifyExp1 = new EntityVerifyExp<UserType>()
            {
                VerifyExp = u => u.UserTypeEnum == addOrEditUserTypeRole.UserTypeEnum ,
              
                VerifyMsg = "已存在该用户类型的角色。"
            };
        
            var entity = new UserType();

            if (addOrEditUserTypeRole.Id == null)
            {
                entity = _mapper.Map<UserType>(addOrEditUserTypeRole);

                //entity.UserTypeEnum = userTypeServiceRepository.Select(t => t.UserTypeEnum).DefaultIfEmpty().Max() + 1;

                await _userTypeRepository.InsertFromDTOAsync(addOrEditUserTypeRole,false, verifyExp1);

            }
            else
            {

                if (addOrEditUserTypeRole.MenuIds.Count > 0)
                {
                    entity = _userTypeRepository.Where(t => t.Id == addOrEditUserTypeRole.Id, true).Include(t => t.UserTypeMenuList).Include(t=>t.UserTypeGroupList).FirstOrDefault().IfNullThrowException();

                }
                else
                {
                    entity = _userTypeRepository.Where(t => t.Id == addOrEditUserTypeRole.Id, true).FirstOrDefault().IfNullThrowException();
                }
                _mapper.Map(addOrEditUserTypeRole, entity);


                await _userTypeRepository.EntityVerifyAsync(entity.Id, verifyExp1);
            }

            var success = await _repository.SaveChangesAsync();

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

        }


        [HttpDelete("{userTypeId:guid}")]
        public async Task<IResponseOutput> DeleteUserTypeRole(Guid userTypeId)
        {
            if ( await _repository.AnyAsync<User>(t => t.UserTypeId == userTypeId))
            {
                //---该用户类型中已存在用户，不能删除
                return ResponseOutput.NotOk(_localizer["UserType_InUse"]);
            }

            var success = await _userTypeRepository.BatchDeleteNoTrackingAsync(t => t.Id == userTypeId);

            return ResponseOutput.Result(success);
        }




        /// <summary>
        ///  通过传递场景枚举 返回对应的下拉框数据   1：是外部   2：是内部  3：是Site调研 4: 邮件接收人，5：邮件抄送人
        /// </summary>
        /// <param name="userTypeSelectEnum"></param>
        /// <returns></returns>
        [HttpGet("{userTypeSelectEnum:int}")]
        public async Task<List<TrialUserType>> GetUserTypeList(UserTypeSelectEnum userTypeSelectEnum)
        {
            var userTypeEnums = new List<UserTypeEnum>();

            if (userTypeSelectEnum == UserTypeSelectEnum.ExternalUser)
            {
                if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.TA)
                {
                    userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.ProjectManager };
                }
                else
                {
                    userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.PI, UserTypeEnum.MIM , UserTypeEnum.IQC};
                }

            }
          
            if (userTypeSelectEnum == UserTypeSelectEnum.SiteSurvey)
            {
                userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.SR, UserTypeEnum.ClinicalResearchCoordinator, UserTypeEnum.CRA };
            }


            if (userTypeSelectEnum == UserTypeSelectEnum.EnrollOrPD_EMailCopy)
            {
                userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.ProjectManager, UserTypeEnum.APM, UserTypeEnum.CPM, UserTypeEnum.SPM };

            }

            if (userTypeSelectEnum == UserTypeSelectEnum.EnrollOrPD_EmailReceive)
            {
                userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.CRA, UserTypeEnum.ClinicalResearchCoordinator };
            }

            if (userTypeSelectEnum == UserTypeSelectEnum.TrialDoc)
            {
                userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.PI, UserTypeEnum.SR, UserTypeEnum.ProjectManager, UserTypeEnum.TA, UserTypeEnum.IQC, UserTypeEnum.IM, UserTypeEnum.MIM  };
            }


            var query = _userTypeRepository.Where(x => x.UserTypeEnum != UserTypeEnum.SuperAdmin)
              .WhereIf(userTypeSelectEnum != UserTypeSelectEnum.None, t => userTypeEnums.Contains(t.UserTypeEnum))
              .OrderBy(t => t.Order).ProjectTo<TrialUserType>(_mapper.ConfigurationProvider);

            return await query.ToListAsync();
        }





        /// <summary>
        /// 项目文档 配置  哪里用户类型下拉
        /// </summary>
        /// <returns></returns>
        public async Task<List<TrialUserType>> GetTrialUserTypeList()
        {
           var userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.PI, UserTypeEnum.SR, UserTypeEnum.ProjectManager, UserTypeEnum.TA, UserTypeEnum.IQC,UserTypeEnum.IM,UserTypeEnum.MIM ,UserTypeEnum.ClinicalResearchCoordinator, UserTypeEnum.CRA };

            var query = _userTypeRepository
               // .Where(x => x.UserTypeEnum != UserTypeEnum.SuperAdmin)
               //.Where(t => !t.UserTypeGroupList.Any(t=> t.Group.Code=="3"))
               .Where( t => userTypeEnums.Contains(t.UserTypeEnum))
               .OrderBy(t => t.Order).ProjectTo<TrialUserType>(_mapper.ConfigurationProvider);

            return await query.ToListAsync();
        }

    }
}
