using IRaCIS.Application.Contracts;
using IRaCIS.Application.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace IRaCIS.Core.Application.Service
{
    [ApiExplorerSettings(GroupName = "Institution")]
    public class CroService(IRepository<CRO> _croRepository,
        IRepository<Trial> _trialRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, ICroService
    {


        /// <summary> 分页获取CRO列表 </summary>
        [HttpPost]
        public async Task<PageOutput<CROCompanyDTO>> GetCroList(CROCompanyQueryDTO inQuery)
        {
            var croQueryable = _croRepository
                .WhereIf(!string.IsNullOrEmpty(inQuery.CROName), t => t.CROName.Contains(inQuery.CROName) || t.CRONameCN.Contains(inQuery.CROName))
                 .WhereIf(!string.IsNullOrEmpty(inQuery.CROCode), t => t.CROCode.Contains(inQuery.CROCode))
                .ProjectTo<CROCompanyDTO>(_mapper.ConfigurationProvider);

            return await croQueryable.ToPagedListAsync(inQuery);


        }

        /// <summary> 根据CRO 名称查询所有CRO 列表 </summary>
        public async Task<IEnumerable<CroSelectDTO>> GetAllCROList(Guid? trialId)
        {
            return await _croRepository
                .WhereIf(trialId == null, t => t.IsTrialLevel == false)
                .WhereIf(trialId != null, t => t.IsTrialLevel == false || t.TrialId == trialId)
                .ProjectTo<CroSelectDTO>(_mapper.ConfigurationProvider, new { isEn_Us = _userInfo.IsEn_Us }).ToListAsync();
        }



        /// <summary> 添加CRO信息 </summary>

        public async Task<IResponseOutput> AddOrUpdateCro(CROCompanyDTO addCroCompanyCommand)
        {

            var exp = new EntityVerifyExp<CRO>()
            {
                VerifyExp = cro => (cro.CROName.Equals(addCroCompanyCommand.CROName) || cro.CRONameCN.Equals(addCroCompanyCommand.CRONameCN)) && cro.IsTrialLevel == false,
                //---已经存在同名的CRO，请确认。
                VerifyMsg = _localizer["CRO_DupName"]
            };

            var cro = await _croRepository.InsertOrUpdateAsync(addCroCompanyCommand, true, exp);



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

        }

        /// <summary> 删除CRO信息 </summary>

        [HttpDelete("{croCompanyId:guid}")]
        public async Task<IResponseOutput> DeleteCro(Guid cROCompanyId)
        {
            if (await _trialRepository.AnyAsync(t => t.CROId == cROCompanyId))
            {
                //---该CRO已经参与项目，不能被删除。
                return ResponseOutput.NotOk(_localizer["CRO_InProject"]);
            }
            //if (_userRoleRepository.Find().Any(t => t.OrganizationId == cROCompanyId))
            //{
            //    return ResponseOutput.NotOk("该CRO下存在用户，暂时无法删除。");
            //}
            var success = await _croRepository.BatchDeleteNoTrackingAsync(x => x.Id == cROCompanyId);

            return ResponseOutput.Result(success);
        }
    }
}
