using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using NPOI.POIFS.Storage;
using Shentun.Peis.Enums;
using Shentun.Peis.Models;
using Shentun.Peis.PatientRegisters;
using Shentun.Peis.PrintReports;
using Shentun.Peis.RegisterCheckItems;
using Shentun.Peis.RegisterCheckPictures;
using Shentun.Peis.RegisterChecks;
using Shentun.Peis.RegisterCheckSuggestions;
using Shentun.Peis.RegisterCheckSummarys;
using Shentun.Peis.SumSummaryReports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
namespace Shentun.Peis.PacsBusiness
{
    /// 
    /// pacs相关接口 免登录
    /// 
    [ApiExplorerSettings(GroupName = "Work")]
    public class PacsBusinessAppService : ApplicationService
    {
        private readonly IConfiguration _configuration;
        private readonly IRepository _registerCheckRepository;
        private readonly IRepository _patientRegisterRepository;
        private readonly IRepository _registerCheckPictureRepository;
        private readonly IRepository _registerCheckPacsRepository;
        private readonly PatientRegisterAppService _patientRegisterAppService;
        private readonly RegisterCheckAppService _registerCheckAppService;
        private readonly RegisterCheckItemAppService _registerCheckItemAppService;
        private readonly RegisterCheckSummaryAppService _registerCheckSummaryAppService;
        private readonly RegisterCheckSuggestionAppService _registerCheckSuggestionAppService;
        private readonly SumSummaryReportAppService _sumSummaryReportAppService;
        private readonly RegisterCheckPictureAppService _registerCheckPictureAppService;
        public PacsBusinessAppService(
            IConfiguration configuration,
            IRepository registerCheckRepository,
            IRepository patientRegisterRepository,
            IRepository registerCheckPictureRepository,
            IRepository registerCheckPacsRepository,
            PatientRegisterAppService patientRegisterAppService,
            RegisterCheckAppService registerCheckAppService,
            RegisterCheckItemAppService registerCheckItemAppService,
            RegisterCheckSummaryAppService registerCheckSummaryAppService,
            RegisterCheckSuggestionAppService registerCheckSuggestionAppService,
            SumSummaryReportAppService sumSummaryReportAppService,
            RegisterCheckPictureAppService registerCheckPictureAppService)
        {
            _configuration = configuration;
            _registerCheckRepository = registerCheckRepository;
            _patientRegisterRepository = patientRegisterRepository;
            _registerCheckPictureRepository = registerCheckPictureRepository;
            _registerCheckPacsRepository = registerCheckPacsRepository;
            _patientRegisterAppService = patientRegisterAppService;
            _registerCheckAppService = registerCheckAppService;
            _registerCheckItemAppService = registerCheckItemAppService;
            _registerCheckSummaryAppService = registerCheckSummaryAppService;
            _registerCheckSuggestionAppService = registerCheckSuggestionAppService;
            _sumSummaryReportAppService = sumSummaryReportAppService;
            _registerCheckPictureAppService = registerCheckPictureAppService;
        }
        /// 
        /// 导入心电图图片  根据检查单号  免登录
        /// 
        /// 
        /// 
        /// 
        [HttpPost("api/app/PacsBusiness/ImportRegisterCheckPictureByCheckRequestNo")]
        public async Task ImportRegisterCheckPictureByCheckRequestNoAsync(ImportRegisterCheckPictureByCheckRequestNoInputDto input)
        {
            Random rd = new Random();
            string AbsolutePath = _configuration.GetValue("PacsVirtualPath:RealPath");
            string AbsoluteName = _configuration.GetValue("PacsVirtualPath:Alias");
            if (string.IsNullOrWhiteSpace(input.PictureBaseStr))
            {
                throw new UserFriendlyException("图片数据不存在");
            }
            var patientRegisterCompleteFlag = (from patientRegister in await _patientRegisterRepository.GetQueryableAsync()
                                               join registerCheck in await _registerCheckRepository.GetQueryableAsync() on patientRegister.Id equals registerCheck.PatientRegisterId
                                               where registerCheck.CheckRequestNo == input.CheckRequestNo
                                               select new
                                               {
                                                   registerCheckId = registerCheck.Id,
                                                   CompleteFlag = patientRegister.CompleteFlag,
                                                   PatientRegisterId = patientRegister.Id
                                               }).ToList();
            if (patientRegisterCompleteFlag.Count == 0)
                throw new UserFriendlyException("体检人员不存在");
            if (patientRegisterCompleteFlag.FirstOrDefault().CompleteFlag == PatientRegisterCompleteFlag.PreRegistration)
                throw new UserFriendlyException("预登记人员不能导入图片");
            if (patientRegisterCompleteFlag.FirstOrDefault().CompleteFlag == PatientRegisterCompleteFlag.SumCheck)
                throw new UserFriendlyException("已总检人员不能导入图片");
            string PatientRegisterId = patientRegisterCompleteFlag.FirstOrDefault().PatientRegisterId.ToString();
            Guid registerCheckId = patientRegisterCompleteFlag.FirstOrDefault().registerCheckId;
            string PictureUrl = ImageHelper.Base64StrToImageInAbsolutePath(AbsolutePath, input.FileName, input.PictureBaseStr,
                PatientRegisterId,
                registerCheckId.ToString(), AbsoluteName);
            if (string.IsNullOrEmpty(PictureUrl))
            {
                throw new UserFriendlyException("图片数据有误");
            }
            var ent = await _registerCheckPictureRepository.FirstOrDefaultAsync(m => m.RegisterCheckId == registerCheckId
               && m.PictureFilename == PictureUrl);
            if (ent != null)
            {
                ent.PictureFilename = PictureUrl;
                await _registerCheckPictureRepository.UpdateAsync(ent);
            }
            else
            {
                var maxDisplayOrder = (await _registerCheckPictureRepository.GetQueryableAsync())
                     .Where(m => m.RegisterCheckId == registerCheckId)
                     .OrderByDescending(o => o.DisplayOrder)
                     .Select(s => s.DisplayOrder)
                     .FirstOrDefault();
                ent = new RegisterCheckPicture
                {
                    DisplayOrder = maxDisplayOrder + 1,
                    IsPrint = 'Y',
                    PictureFilename = PictureUrl,
                    RegisterCheckId = registerCheckId,
                    PictureFileType = '0',
                    LocalPathName = ""
                };
                await _registerCheckPictureRepository.InsertAsync(ent);
            }
        }
        /// 
        /// 导入pacs dicom数据 
        /// 
        /// 
        [HttpPost("api/app/PacsBusiness/ImportPacsDicomData")]
        public async Task ImportPacsDicomDataAsync(ImportPacsDicomDataInputDto input)
        {
            var realPath = _configuration["DicomVirtualPath:RealPath"];
            var requestPath = _configuration["DicomVirtualPath:RequestPath"];
            if (string.IsNullOrWhiteSpace(input.CheckRequestNo))
                throw new UserFriendlyException("条码号不能为空");
            var registerCheckEnt = await _registerCheckRepository.FirstOrDefaultAsync(f => f.CheckRequestNo == input.CheckRequestNo);
            if (registerCheckEnt == null)
                throw new UserFriendlyException("条码号不正确");
            if (input.Details.Any())
            {
                List registerCheckPacss = new List();
                foreach (var item in input.Details)
                {
                    if (!item.FilePathName.Contains(realPath))
                        throw new UserFriendlyException("资源路径跟体检配置不一致");
                    var dicomPathName = item.FilePathName.Replace(realPath, requestPath);
                    registerCheckPacss.Add(new RegisterCheckPacs
                    {
                        CheckDesc = "",
                        CheckResult = "",
                        DicomPathName = dicomPathName,
                        DisplayOrder = input.Details.IndexOf(item) + 1,
                        LocalPathName = item.FilePathName,
                        RegisterCheckId = registerCheckEnt.Id
                    });
                }
                await _registerCheckPacsRepository.InsertManyAsync(registerCheckPacss);
            }
        }
        /// 
        /// 根据检查条码获取dicom文件
        /// 
        /// 
        [HttpPost("api/app/PacsBusiness/GetPacsDicomDataByCheckRequestNo")]
        public async Task> GetPacsDicomDataByCheckRequestNoAsync(CheckRequestNoInputDto input)
        {
            if (string.IsNullOrWhiteSpace(input.CheckRequestNo))
                throw new UserFriendlyException("检查条码不能为空");
            var registerCheckEnt = await _registerCheckRepository.FirstOrDefaultAsync(f => f.CheckRequestNo == input.CheckRequestNo);
            if (registerCheckEnt == null)
                throw new UserFriendlyException("检查条码不存在");
            var registerCheckPacsList = await _registerCheckPacsRepository.GetListAsync(m => m.RegisterCheckId == registerCheckEnt.Id);
            var entListDto = registerCheckPacsList.Select(s => new RegisterCheckPacsDto
            {
                DicomPathName = s.DicomPathName,
                DisplayOrder = s.DisplayOrder,
                LocalPathName = s.LocalPathName
            }).OrderBy(o => o.DisplayOrder).ToList();
            return entListDto;
        }
        /// 
        /// 获取体检人员信息跟项目结果等信息
        /// 
        /// 
        /// 
        [HttpPost("api/app/PacsBusiness/GetPatientRegisterWithCheckResultByCheckRequestNo")]
        public async Task GetPatientRegisterWithCheckResultByCheckRequestNoAsync(CheckRequestNoInputDto input)
        {
            var resultDto = new GetPatientRegisterWithCheckResultByCheckRequestNo();
            var query = (from patientRegister in await _patientRegisterRepository.GetQueryableAsync()
                         join registerCheck in await _registerCheckRepository.GetQueryableAsync() on patientRegister.Id equals registerCheck.PatientRegisterId
                         where registerCheck.CheckRequestNo == input.CheckRequestNo
                         select new
                         {
                             patientRegisterNo = patientRegister.PatientRegisterNo,
                             patientRegisterId = patientRegister.Id,
                             registerCheckId = registerCheck.Id
                         }).FirstOrDefault();
            if (query == null)
            {
                throw new UserFriendlyException("条码不存在");
            }
            resultDto.PatientRegisterDetail = await _patientRegisterAppService.GetAlreadyRegisterPatientRegisterByNoAsync(new PatientRegisterNoInputDto
            {
                PatientRegisterNo = query.patientRegisterNo
            });
            resultDto.RegisterCheckDetail = await _registerCheckAppService.GetRegisterCheckAsync(query.registerCheckId);
            resultDto.RegisterCheckItemDetails = await _registerCheckItemAppService.GetListInRegisterCheckIdAsync(query.registerCheckId, query.patientRegisterId);
            resultDto.RegisterCheckSummaryDetails = await _registerCheckSummaryAppService.GetRegisterCheckSummaryListAsync(query.registerCheckId);
            resultDto.RegisterCheckSuggestionDetails = await _registerCheckSuggestionAppService.GetRegisterCheckSuggestionListAsync(query.registerCheckId);
            resultDto.LastTimeAsbitemResultDetail = await _sumSummaryReportAppService.GetLastTimeAsbitemResultAsync(new RegisterCheckIdInputDto
            {
                RegisterCheckId = query.registerCheckId
            });
            resultDto.registerCheckPictureDetails = await _registerCheckPictureAppService.GetRegisterCheckPictureInRegisterCheckIdAsync(query.registerCheckId);
            
            return resultDto;
        }
    }
}