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;
using EasyCaching.Core;

namespace IRaCIS.Core.Application.Services
{
    [AllowAnonymous, ApiExplorerSettings(GroupName = "Image")]
    public class ImageShareService : BaseService, IImageShareService
    {
        private readonly IEasyCachingProvider _provider;
        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, IEasyCachingProvider provider)
        {

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

        [HttpPost]
        public async Task<IResponseOutput> CreateImageShare(ImageShareCommand imageShareCommand)
        {
        
            var imageShare = _mapper.Map<ImageShare>(imageShareCommand);

            var addEntity = await _imageShareRepository.AddAsync(imageShare);


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

            addEntity.Password = verificationPassWord.ToString();

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

            var days = AppSettings.ImageShareExpireDays;


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

            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("The image resource does not exist");
            }

            if (pWord != imageShare.Password.Trim())
            {
                return ResponseOutput.NotOk("Sharing Password Incorrect");
            }

            if (DateTime.Now > imageShare.ExpireTime)
            {
                return ResponseOutput.NotOk("Resource sharing expires.");
            }

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

            await _provider.SetAsync(vitrualUserId.ToString(), resource.Token, TimeSpan.FromDays(7));

            return ResponseOutput.Ok(resource);

        }
    }
}