using IRaCIS.Application.Interfaces;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.AspNetCore.Mvc;
using Panda.DynamicWebApi.Attributes;
namespace IRaCIS.Application.Services
{
    /// 
    /// 医生文档关联关系维护
    /// 
    [ApiExplorerSettings(GroupName = "Reviewer")]
    public class AttachmentService : BaseService, IAttachmentService
    {
        private readonly IRepository _attachmentrepository;
        public AttachmentService(IRepository attachmentrepository)
        {
            this._attachmentrepository = attachmentrepository;
        }
        /// 
        /// 删除附件
        /// 
        /// 
        /// 
        public async Task 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);
            return ResponseOutput.Result(success);
        }
        /// 
        /// 根据医生Id 和 附件类型,获取记录
        /// 
        /// 医生Id
        /// 附件类型
        /// 
        [HttpGet("{doctorId:guid}/{type}")]
        public async Task> GetAttachmentByType(Guid doctorId, string type)
        {
            var attachmentList = await _attachmentrepository.Where(a => a.DoctorId == doctorId && a.Type.Equals(type)).ProjectTo(_mapper.ConfigurationProvider).ToListAsync();
            attachmentList.ForEach(t => t.FullPath =  t.Path + "?access_token=" + _userInfo.UserToken);
            return attachmentList;
        }
        /// 
        /// 获取单个医生的多种证书附件
        /// 
        /// 医生Id
        /// 类型数组
        /// 
        [HttpPost("{doctorId:guid}")]
        public  async Task> 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(_mapper.ConfigurationProvider).ToListAsync();
            attachmentList.ForEach(t => t.FullPath =  t.Path + "?access_token=" + _userInfo.UserToken);
            return attachmentList;
        }
        /// 
        /// 根据医生Id获取医生附件
        /// 
        /// 医生Id
        /// 
        [HttpGet("{doctorId:guid}")]
        public async Task> GetAttachments(Guid doctorId)
        {
            var attachmentList =await _attachmentrepository.Where(a => a.DoctorId == doctorId).OrderBy(s => s.Type).ThenBy(m => m.CreateTime).ProjectTo(_mapper.ConfigurationProvider).ToListAsync();
            attachmentList.ForEach(t => t.FullPath =  t.Path + "?access_token=" + _userInfo.UserToken);
            return attachmentList;
        }
        [NonDynamicMethod]
        public async Task GetDetailById(Guid attachmentId)
        {
            var attachment = await _attachmentrepository.FirstOrDefaultAsync(a => a.Id == attachmentId).IfNullThrowException();
            var temp= _mapper.Map(attachment);
            temp.FullPath =  temp.Path + "?access_token=" + _userInfo.UserToken;
            return temp;
        }
        /// 
        /// 保存多个附件
        /// 
        /// 
        /// 
        public async Task> SaveAttachments(IEnumerable attachmentList)
        {
            var attachments = _mapper.Map>(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 _repository.AddRangeAsync(newAttachment);
            await _repository.SaveChangesAsync();
            //_doctorAttachmentRepository.AddRange(newAttachment);
            //_doctorAttachmentRepository.SaveChanges();
            var list = _mapper.Map>(attachments).ToList();
            list.ForEach(t => t.FullPath =  t.Path + "?access_token=" + _userInfo.UserToken);
            return list;
        }
        public async Task> AddAttachment(AttachmentDTO attachment)
        {
            var newAttachment = _mapper.Map(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 _repository.AddAsync(newAttachment);
            var success = await _repository.SaveChangesAsync();
            return ResponseOutput.Result(success, attachment);
        }
        [NonDynamicMethod]
        public async Task 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;
        }
        /// 
        /// 将简历设置为官方简历
        /// 
        /// 
        /// 
        /// 
        /// 
       
        [HttpPost("{doctorId:guid}/{attachmentId:guid}/{language}")]
        public async Task SetOfficial(Guid doctorId, Guid attachmentId, int language)
        {
            var resumeList = await _attachmentrepository.Where(t => t.DoctorId == doctorId && t.Type == "Resume" && t.Language == language).ToListAsync();
            foreach (var item in resumeList)
            {
                if (item.Id == attachmentId) item.IsOfficial = true;
                else item.IsOfficial = false;
                await _repository.UpdateAsync(item);
            }
           
            return ResponseOutput.Result(await _repository.SaveChangesAsync());
        }
        /// 
        /// 设置简历的语言类型
        /// 
        /// 
        /// 
        /// 0-未设置,1-中文,2-英文
        /// 
       
        [HttpPost("{doctorId:guid}/{attachmentId:guid}/{language}")]
        public async Task 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);
        }
    }
}