//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2024-03-22 15:44:31 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------

using FellowOakDicom.Network;
using FellowOakDicom.Network.Client;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using Microsoft.AspNetCore.Mvc;
namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// DicomAEService
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TrialDicomAEService(IRepository<TrialDicomAE> _dicomAERepository,
        IRepository<Trial> _trialRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IDicomAEService
    {


        [HttpPost]
        public async Task<IResponseOutput<PageOutput<DicomAEView>>> GetDicomAEList(DicomAEQuery inQuery)
        {

            var dicomAEQueryable = _dicomAERepository
                               .WhereIf(!string.IsNullOrWhiteSpace(inQuery.IP), t => t.IP.Contains(inQuery.IP))
                               .WhereIf(inQuery.Port != null, t => t.Port == inQuery.Port)
                               .WhereIf(!string.IsNullOrWhiteSpace(inQuery.CalledAE), t => t.CalledAE.Contains(inQuery.CalledAE))
                               .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Description), t => t.Description.Contains(inQuery.Description))
                               .WhereIf(!string.IsNullOrWhiteSpace(inQuery.Modality), t => t.Modality.Contains(inQuery.Modality))
                               .ProjectTo<DicomAEView>(_mapper.ConfigurationProvider);




            var pageList = await dicomAEQueryable.ToPagedListAsync(inQuery);


            return ResponseOutput.Ok(pageList);
        }


        /// <summary>
        /// 获取项目dicom AE 配置信息，otherinfo里面有IsPACSConnect  IsTrialPACSConfirmed
        /// </summary>
        /// <param name="trialId"></param>
        /// <returns></returns>
        public async Task<IResponseOutput<DicomAEView>> GetTrialDicomAE(Guid trialId)
        {
            var dicomAE = _dicomAERepository.Where(t => t.TrialId == trialId).ProjectTo<DicomAEView>(_mapper.ConfigurationProvider).FirstOrDefault();
            var trialConfig = await _trialRepository.Where(t => t.Id == trialId).Select(t => new { t.IsPACSConnect, t.IsTrialPACSConfirmed }).FirstOrDefaultAsync();
            return ResponseOutput.Ok(dicomAE, trialConfig);

        }


        public async Task<IResponseOutput> AddOrUpdateDicomAE(DicomAEAddOrEdit addOrEditDicomAE)
        {
            var verifyExp1 = new EntityVerifyExp<TrialDicomAE>()
            {
                VerifyExp = u => u.IP == addOrEditDicomAE.IP && u.Port == addOrEditDicomAE.Port && u.TrialId == addOrEditDicomAE.TrialId,

                //"不允许添加相同的IP和端口的记录"
                VerifyMsg = _localizer["TrialDicomAE_RepeatIPAndPort"]
            };

            var verifyExp2 = new EntityVerifyExp<TrialDicomAE>()
            {
                VerifyExp = u => u.CalledAE == addOrEditDicomAE.CalledAE,

                //"AE名称不能与其他项目相同"
                VerifyMsg = _localizer["TrialDicomAE_RepeatCalledAE"]
            };

            var verifyExp3 = new EntityVerifyExp<TrialDicomAE>()
            {
                VerifyExp = u => u.TrialId == addOrEditDicomAE.TrialId,

                //"AE名称不能与其他项目相同"
                VerifyMsg = "该项目只允许添加一条dicom AE记录（前端对接有bug时出现）"
            };

            //var verifyExp2 = new EntityVerifyExp<TrialDicomAE>()
            //{
            //    VerifyExp = u =>  u.TrialId == addOrEditDicomAE.TrialId,

            //    VerifyMsg = "只允许配置一条记录",
            //    IsVerify=addOrEditDicomAE.Id==null
            //};

            await _trialRepository.UpdatePartialFromQueryAsync(t => t.Id == addOrEditDicomAE.TrialId, u => new Trial() { IsPACSConnect = addOrEditDicomAE.IsPACSConnect }, true);


            if (addOrEditDicomAE.IsPACSConnect)
            {
                //  在此处拷贝automapper 映射       
                var entity = await _dicomAERepository.InsertOrUpdateAsync(addOrEditDicomAE, true, verifyExp3, verifyExp1, verifyExp2);

                return ResponseOutput.Ok(entity.Id.ToString());
            }
            else
            {
                return ResponseOutput.Ok();
            }


        }


        [HttpDelete("{dicomAEId:guid}")]
        public async Task<IResponseOutput> DeleteDicomAE(Guid dicomAEId)
        {
            var success = await _dicomAERepository.DeleteFromQueryAsync(t => t.Id == dicomAEId, true);
            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 测试scp server 是否可以连接
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> TestSCPServerConnect(TestAECommand inCommand)
        {
            try
            {
                var client = DicomClientFactory.Create(inCommand.IP, inCommand.Port, false, "test-callingAE", inCommand.CalledAE);

                client.NegotiateAsyncOps();

                await client.AddRequestAsync(new DicomCEchoRequest());

                // 创建一个超时任务，设置超时时间为1秒
                var timeoutTask = Task.Delay(TimeSpan.FromSeconds(3));

                // 发送 DICOM 请求
                var sendTask = client.SendAsync();

                // 等待任务完成，若超时任务先完成则抛出超时异常
                if (await Task.WhenAny(sendTask, timeoutTask) == timeoutTask)
                {
                    throw new TimeoutException("DICOM 请求超时。");
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }


        }


    }
}
