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

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

        public UserTypeRoleService(IRepository<UserType> userTypeServiceRepository)
        {
            this.userTypeServiceRepository = userTypeServiceRepository;
        }

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

            var userTypeRoleQueryable = userTypeServiceRepository.Where(t=>t.UserTypeEnum !=UserTypeEnum.SuperAdmin)
                .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 entity = new UserType();

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

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

                await _repository.AddAsync(entity);


            }
            else
            {

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

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

            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("该用户类型中已存在用户，不能删除");
            }

            var success = await userTypeServiceRepository.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)
            {
                userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.CPM, UserTypeEnum.SPM, UserTypeEnum.CPM, UserTypeEnum.SMM, UserTypeEnum.CMM, UserTypeEnum.EA };
            }


            if (userTypeSelectEnum == UserTypeSelectEnum.InnerUser)
            {
                //userTypeEnums = new List<UserTypeEnum>() { UserTypeEnum.IQC, UserTypeEnum.APM, UserTypeEnum.MIM, UserTypeEnum.QA ,UserTypeEnum.MW};

                userTypeEnums = new List<UserTypeEnum>() {  UserTypeEnum.IndependentReviewer, UserTypeEnum.ClinicalResearchCoordinator,UserTypeEnum.ProjectManager };

                if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.NormalAdmin)
                {
                    userTypeEnums.Add(UserTypeEnum.ProjectManager);
                }
            }

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

            }


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

            }

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


            }



            var query = userTypeServiceRepository.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 query = userTypeServiceRepository.Where(x => x.UserTypeEnum != UserTypeEnum.NormalAdmin)
               //.Where(t => t.Type == UserTypeGroup.TrialUser)
               .OrderBy(t => t.Order).ProjectTo<TrialUserType>(_mapper.ConfigurationProvider);

            return await query.ToListAsync();
        }

    }
}
