using IRaCIS.Core.Application.Contracts.Dicom.DTO;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using IRaCIS.Core.Application.Auth;

namespace IRaCIS.Core.Application.Services
{
    [AllowAnonymous, ApiExplorerSettings(GroupName = "Image")]
    public class ImageShareService : BaseService, IImageShareService
    {

        private readonly IRepository<ImageShare> _imageShareRepository;
        private readonly IRepository<DicomStudy> _studyRepository;
        private readonly IConfiguration _configuration;
        private readonly ITokenService _tokenService;

        public ImageShareService(IRepository<ImageShare> imageShareRepository, IRepository<DicomStudy> studyRepository, IConfiguration configuration, ITokenService tokenService)
        {

            _imageShareRepository = imageShareRepository;
            _studyRepository = studyRepository;
            _configuration = configuration;
            _tokenService = tokenService;
        }

        [HttpPost]
        public async Task<IResponseOutput> CreateImageShare(ImageShareCommand imageShareCommand)
        {
            if (imageShareCommand.StudyId == null)
            {

                #region 上传不按照检查批次上传，基线没传，数据可能出错

                //var subjectVisit1 = _subjectVisitRepository.FirstOrDefault(t =>
                //    t.TrialId == imageShareCommand.TrialId && t.SubjectId == imageShareCommand.SubjectId &&
                //    t.VisitNum == 1);

                //if (subjectVisit1 == null)
                //{
                //    return ResponseOutput.NotOk("当前无影像数据，无法分享！");
                //}

                //imageShareCommand.StudyId =
                //    _studyRepository.GetAll().First(t => t.SubjectVisitId == subjectVisit1.Id&&t.Status != (int)StudyStatus.Abandon).Id;

                #endregion

                var studyIds = await _studyRepository.AsQueryable()
                    .Where(t => t.TrialId == imageShareCommand.TrialId && t.SubjectId == imageShareCommand.SubjectId &&
                                t.SiteId == imageShareCommand.SiteId)
                    .Select(u => u.Id).ToListAsync();

                if (!studyIds.Any())
                {
                    return ResponseOutput.NotOk("当前检查没有影像可以分享。 ");
                }

                imageShareCommand.StudyId = studyIds.First();

            }

            //验证码 4位
            int verificationPassWord = new Random().Next(1000, 10000);

            imageShareCommand.Password = verificationPassWord.ToString();

            //配置文件读取过期时间

            var days = AppSettings.ImageShareExpireDays;


            imageShareCommand.ExpireTime = DateTime.Now.AddDays(days);

            var imageShare = _mapper.Map<ImageShare>(imageShareCommand);

            await _imageShareRepository.AddAsync(imageShare);

            var success = await _imageShareRepository.SaveChangesAsync();

            return ResponseOutput.Result(success, new { ResourceId = imageShare.Id, Password = verificationPassWord.ToString() });


        }

        [HttpGet, Route("{resourceId:guid}/{password}")]
        public async Task<IResponseOutput> VerifyShareImage(Guid resourceId, string password)
        {
            var pWord = password.Trim();
            var imageShare = await _imageShareRepository.FirstOrDefaultAsync(t => t.Id == resourceId);

            if (imageShare == null)
            {
                return ResponseOutput.NotOk("资源不存在。");
            }

            if (pWord != imageShare.Password.Trim())
            {
                return ResponseOutput.NotOk("分享密码错误。");
            }

            if (DateTime.Now > imageShare.ExpireTime)
            {
                return ResponseOutput.NotOk("资源分享过期。");
            }

            var resource = new ResourceInfo()
            {
                StudyId = imageShare.StudyId,
                Token = _tokenService.GetToken(IRaCISClaims.Create(new UserBasicInfo()
                {
                    Id = Guid.Empty,
                    IsReviewer = false,
                    IsAdmin = false,
                    RealName = "Share001",
                    UserName = "Share001",
                    Sex = 0,
                    //UserType = "ShareType",
                    UserTypeEnum = UserTypeEnum.ShareImage,
                    Code = "ShareCode001",
                }))
            };


            return ResponseOutput.Ok(resource);

        }
    }
}