using IRaCIS.Application.Contracts;
using IRaCIS.Application.Interfaces;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.AspNetCore.Mvc;
using Panda.DynamicWebApi.Attributes;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 医生文档关联关系维护
    /// </summary>
    [ApiExplorerSettings(GroupName = "Reviewer")]
    public class AttachmentService(IRepository<Attachment> _attachmentrepository,
        IRepository<Dictionary> _dictionaryRepository,
        IRepository<Enroll> _enrollRepository,
        IOSSService _oSSService,
        IRepository<Doctor> _doctorrepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IAttachmentService
    {


        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>

        public async Task<IResponseOutput> DeleteAttachment([FromBody] AttachementCommand param)
        {
            //var attachment = _doctorAttachmentApp.GetDetailById(id);
            //string file = HostingEnvironment.MapPath(attachment.Path);

            //if (File.Exists(file))
            //{
            //    File.Delete(file);
            //}
            //var temp = HostingEnvironment.MapPath(param.Path);
            //if (File.Exists(temp))
            //{
            //    File.Delete(temp);
            //}

            var success = await _attachmentrepository.BatchDeleteNoTrackingAsync(a => a.Id == param.Id);

            await _doctorrepository.BatchUpdateNoTrackingAsync(x => x.GCPId == param.Id, x => new Doctor()
            {
                GCPId= default(Guid),
            });
            return ResponseOutput.Result(success);
        }


        /// <summary>
        /// 根据医生Id 和 附件类型，获取记录
        /// </summary>
        /// <param name="doctorId">医生Id</param>
        /// <param name="type">附件类型</param>
        /// <returns></returns>
        [HttpGet("{doctorId:guid}/{type}")]
        public async Task<IEnumerable<AttachmentDTO>> GetAttachmentByType(Guid doctorId, string type)
        {
            var attachmentList = await _attachmentrepository.Where(a => a.DoctorId == doctorId && a.Type.Equals(type)).ProjectTo<AttachmentDTO>(_mapper.ConfigurationProvider).ToListAsync();
            attachmentList.ForEach(t => t.FullPath = t.Path + "?access_token=" + _userInfo.UserToken);

            return attachmentList;
        }

        /// <summary>
        /// 获取单个医生的多种证书附件
        /// </summary>
        /// <param name="doctorId">医生Id</param>
        /// <param name="types">类型数组</param>
        /// <returns></returns>
        [HttpPost("{doctorId:guid}")]
        public async Task<IEnumerable<AttachmentDTO>> GetAttachmentByTypes(Guid doctorId, string[] types)
        {

            var attachmentList = await _attachmentrepository.Where(a => a.DoctorId == doctorId && types.Contains(a.Type)).OrderBy(s => s.Type).ThenBy(m => m.CreateTime).ProjectTo<AttachmentDTO>(_mapper.ConfigurationProvider).ToListAsync();
            attachmentList.ForEach(t => t.FullPath = t.Path + "?access_token=" + _userInfo.UserToken);

            return attachmentList;
        }

        /// <summary>
        /// 根据医生Id获取医生附件
        /// </summary>
        /// <param name="doctorId">医生Id</param>
        /// <returns></returns>
        [HttpGet("{doctorId:guid}")]
        public async Task<IEnumerable<AttachmentDTO>> GetAttachments(Guid doctorId)
        {
            var attachmentList = await _attachmentrepository.Where(a => a.DoctorId == doctorId).OrderBy(s => s.Type).ThenBy(m => m.CreateTime).ProjectTo<AttachmentDTO>(_mapper.ConfigurationProvider).ToListAsync();
            attachmentList.ForEach(t => t.FullPath = t.Path + "?access_token=" + _userInfo.UserToken);

            return attachmentList;
        }


        /// <summary>
        /// 获取项目医生附件
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<AttachmentDTO>> GetTrialAttachments(GetTrialAttachmentsInDto inDto)
        {
        


            var dicList=await _dictionaryRepository.Where(x => x.Parent.Code == "CertificateFileType").Select(x=>x.Code).ToListAsync();

            var attachmentList = await _attachmentrepository
                .Where(a =>a.Doctor.EnrollList.Any(x=>x.TrialId == inDto.TrialId && x.EnrollStatus >= EnrollStatus.InviteIntoGroup)|| a.TrialId == inDto.TrialId)
                .WhereIf(inDto.DoctorId!=null,x=>x.DoctorId==inDto.DoctorId)
                 .WhereIf(inDto.IsAuthorizedView != null, x => x.IsAuthorizedView == inDto.IsAuthorizedView)
                  .WhereIf(inDto.Type.IsNotNullOrEmpty(), x => x.Type == inDto.Type)
                  .WhereIf(inDto.FileName.IsNotNullOrEmpty(), x => inDto.FileName.Contains(x.FileName))

                .Where(a => dicList.Contains(a.Type)||a.Type==string.Empty)
                  


                .ProjectTo<AttachmentDTO>(_mapper.ConfigurationProvider, new { TrialId = inDto.TrialId }).ToPagedListAsync(inDto);


            return attachmentList;

        }


        /// <summary>
        /// 获取医生列表
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetTrialDoctorListOutDto>> GetTrialDoctorList(GetTrialDoctorSelectInDto inDto)
        {
          var result=  await _enrollRepository.Where(x => x.TrialId == inDto.TrialId && x.EnrollStatus >= EnrollStatus.InviteIntoGroup).Select(x => x.Doctor)

                .ProjectTo<GetTrialDoctorListOutDto>(_mapper.ConfigurationProvider).OrderBy(x=>x.BlindName).ToListAsync();


            return result;
        }


        /// <summary>
        /// 修改稽查状态
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SetAuthorizedView(SetAttachmentAuthorizedView inDto)
        {
            await _attachmentrepository.UpdatePartialFromQueryAsync(x => inDto.Ids.Contains(x.Id), x => new Attachment() { IsAuthorizedView = inDto.IsAuthorizedView });

            await _attachmentrepository.SaveChangesAsync();
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> DeleteAttachment(DeleteAttachment inDto)
        {
            var success = await _attachmentrepository.DeleteFromQueryAsync(t => inDto.Ids.Contains(t.Id));
            await _attachmentrepository.SaveChangesAsync();
            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 上传项目医生
        /// </summary>
        /// <param name="attachmentList"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<AttachmentDTO>> SaveTrialAttachments(IEnumerable<AttachmentDTO> attachmentList)
        {
          
                foreach (var item in attachmentList)
                {
                    if (item.DoctorId != null)
                    {
                        await _attachmentrepository.BatchDeleteNoTrackingAsync(a => a.DoctorId == item.DoctorId && a.Type == item.Type);
                    }
                }

                var attachments = _mapper.Map<IEnumerable<Attachment>>(attachmentList).ToList();
                var newAttachment = attachments.Where(t => t.Id == Guid.Empty);
                await _attachmentrepository.AddRangeAsync(newAttachment);
                await _attachmentrepository.SaveChangesAsync();

                var list = _mapper.Map<IEnumerable<AttachmentDTO>>(attachments).ToList();

                list.ForEach(t => t.FullPath = t.Path + "?access_token=" + _userInfo.UserToken);

                return list;
         
        }

        /// <summary>
        /// 更新医生资质
        /// </summary>
        /// <param name="attachment"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> UpdateTrialAttachments(AttachmentDTO attachment)
        {

            if (!attachment.Path.Contains(attachment.DoctorId.ToString()))
            {
                var attachmentData= await _attachmentrepository.Where(a => a.Id == attachment.Id).FirstNotNullAsync();

                var  fileName= attachmentData.Path.Split("/").Last();


                attachment.Path = $"/systemData/reviewe/{attachment.Type}/{attachment.DoctorId}/{fileName}";

                await  _oSSService.MoveObject(attachmentData.Path, attachment.Path);

            }

            if (attachment.DoctorId != null)
            {
                await _attachmentrepository.DeleteFromQueryAsync(a =>a.Id!=attachment.Id&& a.DoctorId == attachment.DoctorId && a.Type == attachment.Type);
            }

            attachment.UpdateTime = DateTime.Now;
            await _attachmentrepository.UpdateFromDTOAsync(attachment);

            await _attachmentrepository.SaveChangesAsync();
            return ResponseOutput.Ok();
        }



        [NonDynamicMethod]
        public async Task<AttachmentDTO> GetDetailById(Guid attachmentId)
        {
            var attachment = await _attachmentrepository.FirstOrDefaultAsync(a => a.Id == attachmentId).IfNullThrowException();
            var temp = _mapper.Map<AttachmentDTO>(attachment);
            temp.FullPath = temp.Path + "?access_token=" + _userInfo.UserToken;
            return temp;
        }

        /// <summary>
        /// 保存多个附件
        /// </summary>
        /// <param name="attachmentList"></param>
        /// <returns></returns>
        public async Task<IEnumerable<AttachmentDTO>> SaveAttachments(IEnumerable<AttachmentDTO> attachmentList)
        {
            var attachments = _mapper.Map<IEnumerable<Attachment>>(attachmentList).ToList();

            //1 是中文  2是英文  中英文第一份简历默认设置为官方

            var zhCount = attachments.Count(t => t.Language == 1);
            var usCount = attachments.Count(t => t.Language == 2);

            if (zhCount == 1)
            {
                var k = attachments.First(t => t.Language == 1);
                k.IsOfficial = true;
            }
            if (usCount == 1)
            {
                var k = attachments.First(t => t.Language == 2);
                k.IsOfficial = true;
            }


            //处理重传
            var reUpload = attachmentList.FirstOrDefault(t => t.ReUpload == true);
            if (reUpload != null)
            {
                //因为界面现实的列表用了 接口返回的列表，所以要把返回的模型对应的字段也要更改
                var attach = attachments.First(t => t.Id == reUpload.Id);
                attach.CreateTime = DateTime.Now;


                //重传的时候，发现 相同语言的官方简历数量为2  那么将重传的简历设置为非官方
                if (attachments.Count(t => t.Language == reUpload.Language && t.IsOfficial) == 2)
                {
                    await _attachmentrepository.BatchUpdateNoTrackingAsync(t => t.Id == reUpload.Id, u => new Attachment()
                    {
                        Path = reUpload.Path,
                        CreateTime = DateTime.Now,
                        Language = reUpload.Language,
                        IsOfficial = false
                    });
                    attach.IsOfficial = false;
                }
                else  //相同语言的重传  
                {
                    await _attachmentrepository.BatchUpdateNoTrackingAsync(t => t.Id == reUpload.Id, u => new Attachment()
                    {
                        Path = reUpload.Path,
                        CreateTime = DateTime.Now,
                        Language = reUpload.Language
                    });

                }

            }


            var newAttachment = attachments.Where(t => t.Id == Guid.Empty);

            await _attachmentrepository.AddRangeAsync(newAttachment);
            await _attachmentrepository.SaveChangesAsync();

            //_doctorAttachmentRepository.AddRange(newAttachment);
            //_doctorAttachmentRepository.SaveChanges();

            var list = _mapper.Map<IEnumerable<AttachmentDTO>>(attachments).ToList();

            list.ForEach(t => t.FullPath = t.Path + "?access_token=" + _userInfo.UserToken);

            return list;
        }

        public async Task<IResponseOutput<AttachmentDTO>> AddAttachment(AttachmentDTO attachment)
        {

            var newAttachment = _mapper.Map<Attachment>(attachment);
            //如果这个医生不存在 这个语言的官方简历  就设置为官方简历
            if (!await _attachmentrepository.AnyAsync(t => t.Type == "Resume" && t.DoctorId == attachment.DoctorId && t.Language == attachment.Language && t.IsOfficial))
            {
                newAttachment.IsOfficial = true;

                attachment.IsOfficial = true;
            }

            await _attachmentrepository.AddAsync(newAttachment);
            var success = await _attachmentrepository.SaveChangesAsync();
            return ResponseOutput.Result(success, attachment);
        }


        [NonDynamicMethod]
        public async Task<string> GetDoctorOfficialCV(int language, Guid doctorId)
        {
            var result = await _attachmentrepository.FirstOrDefaultAsync(a => a.DoctorId == doctorId &&
           a.IsOfficial && a.Type.Equals("Resume") && a.Language == language);
            if (result != null)
            {
                return result.Path;
            }
            return string.Empty;
        }


        /// <summary>
        /// 将简历设置为官方简历
        /// </summary>
        /// <param name="doctorId"></param>
        /// <param name="attachmentId"></param>
        /// <param name="language"></param>
        /// <returns></returns>

        [HttpPost("{doctorId:guid}/{attachmentId:guid}/{language}")]
        public async Task<IResponseOutput> SetOfficial(Guid doctorId, Guid attachmentId, int language)
        {
            var resumeList = await _attachmentrepository.Where(t => t.DoctorId == doctorId && t.Type == "Resume" && t.Language == language, true).ToListAsync();
            foreach (var item in resumeList)
            {
                if (item.Id == attachmentId) item.IsOfficial = true;
                else item.IsOfficial = false;
            }

            return ResponseOutput.Result(await _attachmentrepository.SaveChangesAsync());
        }

        /// <summary>
        /// 设置简历的语言类型
        /// </summary>
        /// <param name="doctorId"></param>
        /// <param name="attachmentId"></param>
        /// <param name="language">0-未设置，1-中文，2-英文</param>
        /// <returns></returns>

        [HttpPost("{doctorId:guid}/{attachmentId:guid}/{language}")]
        public async Task<IResponseOutput> SetLanguage(Guid doctorId, Guid attachmentId, int language)
        {
            bool result = await _attachmentrepository.BatchUpdateNoTrackingAsync(t => t.Id == attachmentId, a => new Attachment
            {
                Language = language,
                IsOfficial = false
            });
            return ResponseOutput.Result(result);
        }


    }
}
