using IRaCIS.Application.Contracts;
using IRaCIS.Application.Interfaces;
using IRaCIS.Core.Domain.Share;
using Medallion.Threading;
using Microsoft.AspNetCore.Mvc;
using Site = IRaCIS.Core.Domain.Models.Site;

namespace IRaCIS.Core.Application.Service
{
    [ApiExplorerSettings(GroupName = "Institution")]
    public class SiteService(IRepository<Site> _siteRepository,
        IRepository<TrialSiteUserRole> _trialSiteUserRoleRepository,
        IDistributedLockProvider _distributedLockProvider,
        IRepository<TrialSite> _trialSiteRepository,
        IRepository<Hospital> _hospitalRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, ISiteService
    {


        /// <summary> 分页获取研究中心列表 </summary>
        [HttpPost]
        public async Task<PageOutput<SiteSelectDTO>> GetSiteList(SiteQueryParam inQuery)
        {

            var siteQueryable = _siteRepository
                   .WhereIf(!string.IsNullOrWhiteSpace(inQuery.SiteName), t => t.SiteName.Contains(inQuery.SiteName) || t.SiteNameCN.Contains(inQuery.SiteName))
                   .WhereIf(!string.IsNullOrWhiteSpace(inQuery.AliasName), t => t.AliasName.Contains(inQuery.AliasName))
                   .WhereIf(!string.IsNullOrWhiteSpace(inQuery.City), t => t.City.Contains(inQuery.City))
                   .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Country), t => t.Country.Contains(inQuery.Country))
                   .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Province), t => t.Province.Contains(inQuery.Province))
                   .ProjectTo<SiteSelectDTO>(_mapper.ConfigurationProvider, new { isEn_Us = _userInfo.IsEn_Us });


            return await siteQueryable.ToPagedListAsync(inQuery);


        }

        public async Task<IEnumerable<SiteSelectionDTO>> GetAllSiteList()
        {
            return await _siteRepository.ProjectTo<SiteSelectionDTO>(_mapper.ConfigurationProvider).ToListAsync();
        }

        [HttpPost]
        public async Task<PageOutput<TrialSiteAddView>> GetTrialSiteList(TrialSiteInQuery inQuery)
        {
            var query = _trialSiteRepository.Where(t => t.SiteId == null)
                .WhereIf(!string.IsNullOrEmpty(inQuery.TrialSiteName), t => t.TrialSiteName.Contains(inQuery.TrialSiteName) || t.TrialSiteAliasName.Contains(inQuery.TrialSiteName))
                .WhereIf(!string.IsNullOrEmpty(inQuery.TrialCode), t => t.Trial.TrialCode.Contains(inQuery.TrialCode))
                .Select(t => new TrialSiteAddView()
                {
                    TrialCode = t.Trial.TrialCode,
                    TrialSiteAliasName = t.TrialSiteAliasName,
                    TrialSiteId = t.Id,
                    TrialSiteName = t.TrialSiteName
                });

            return await query.ToPagedListAsync(inQuery, nameof(TrialSiteAddView.TrialCode));
        }

        /// <summary> 添加研究中心 </summary>

        public async Task<IResponseOutput> AddOrUpdateSite(SiteCommand siteCommand)
        {

            var exp = new EntityVerifyExp<Site>()
            {
                VerifyExp = h => h.SiteName.Equals(siteCommand.SiteName) || h.SiteNameCN.Equals(siteCommand.SiteNameCN),
                //---已经存在同名的中心，请确认。
                VerifyMsg = _localizer["Site_DupName"]
            };

            var @lock = _distributedLockProvider.CreateLock($"SiteAdd");

            using (await @lock.AcquireAsync())
            {
                if (siteCommand.Id == null)
                {

                    siteCommand.Code = await _siteRepository.Select(t => t.Code).DefaultIfEmpty().MaxAsync() + 1;

                    siteCommand.SiteCode = AppSettings.GetCodeStr(siteCommand.Code, nameof(Site));
                }

                var site = await _siteRepository.InsertOrUpdateAsync(siteCommand, true, exp);

                //手动解绑医院与site的关系
                if (siteCommand.HospitalId == null && site.HospitalId != null)
                {
                    await _hospitalRepository.BatchUpdateNoTrackingAsync(t => t.Id == site.HospitalId, u => new Hospital() { SiteId = null });
                }

                //手动绑
                if (siteCommand.HospitalId != null)
                {
                    await _hospitalRepository.BatchUpdateNoTrackingAsync(t => t.Id == siteCommand.HospitalId, u => new Hospital() { SiteId = site.Id });
                }

                if (siteCommand.TrialSiteId != null)
                {
                    await _trialSiteRepository.BatchUpdateNoTrackingAsync(t => t.Id == siteCommand.TrialSiteId, u => new TrialSite() { SiteId = site.Id });
                }

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

            }



        }

        /// <summary> 删除研究中心 </summary>

        [HttpDelete("{siteId:guid}")]
        public async Task<IResponseOutput> DeleteSite(Guid siteId)
        {

            if (await _trialSiteUserRoleRepository.AnyAsync(t => t.TrialSite.SiteId == siteId))
            {
                //---该中心已经加入项目，不可以被删除。
                return ResponseOutput.NotOk(_localizer["Site_InProject"]);
            }

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