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

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


        /// <summary> 分页获取申办方列表 </summary>
        [HttpPost]
        public async Task<PageOutput<SponsorDTO>> GetSponsorList(SponsorQueryDTO inQuery)
        {

            var sponsorQueryable = _sponsorRepository
                .WhereIf(!string.IsNullOrWhiteSpace(inQuery.SponsorName), t => t.SponsorName.Contains(inQuery.SponsorName) || t.SponsorNameCN.Contains(inQuery.SponsorName))
                .WhereIf(!string.IsNullOrEmpty(inQuery.SponsorCode), t => t.SponsorCode.Contains(inQuery.SponsorCode))
                .ProjectTo<SponsorDTO>(_mapper.ConfigurationProvider);

            return await sponsorQueryable.ToPagedListAsync(inQuery);

        }

        /// <summary> 分页获取申办方列表 </summary>
        public async Task<IEnumerable<SponsorSelectDTO>> GetAllSponsorList(Guid? trialId)
        {

            var sponsorQueryable = _sponsorRepository
                .WhereIf(trialId == null, t => t.IsTrialLevel == false)
                .WhereIf(trialId != null, t => t.IsTrialLevel == false || t.TrialId == trialId)
                .ProjectTo<SponsorSelectDTO>(_mapper.ConfigurationProvider, new { isEn_Us = _userInfo.IsEn_Us });
            return await sponsorQueryable.ToListAsync();
        }

        /// <summary> 添加申办方 </summary>
        public async Task<IResponseOutput> AddOrUpdateSponsor(SponsorCommand sponsorCommand)
        {
            var exp = new EntityVerifyExp<Sponsor>()
            {
                VerifyExp = h => (h.SponsorName.Equals(sponsorCommand.SponsorName) || h.SponsorNameCN.Equals(sponsorCommand.SponsorNameCN)) && h.IsTrialLevel == false,
                //---已经存在同名的申办方，请确认。
                VerifyMsg = _localizer["Sponsor_DupName"]
            };

            var sponsor = await _sponsorRepository.InsertOrUpdateAsync(sponsorCommand, true, exp);

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



        }

        /// <summary> 删除申办方 </summary>
        [HttpDelete("{sponsorId:guid}")]

        public async Task<IResponseOutput> DeleteSponsor(Guid sponsorId)
        {
            if (await _trialRepository.AnyAsync(t => t.SponsorId == sponsorId))
            {
                //---该申办方已经加入项目，不允许删除。
                return ResponseOutput.NotOk(_localizer["Sponsor_InProject"]);
            }

            var success = await _sponsorRepository.BatchDeleteNoTrackingAsync(x => x.Id == sponsorId);
            return ResponseOutput.Result(success);
        }
    }
}
