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
{
    /// <summary>
    /// 医生文档关联关系维护
    /// </summary>
    [ApiExplorerSettings(GroupName = "Reviewer")]
    public class AttachmentService : BaseService, IAttachmentService
    {
        private readonly IRepository<Attachment> _attachmentrepository;

        public AttachmentService(IRepository<Attachment> attachmentrepository)
        {
            this._attachmentrepository = attachmentrepository;
        }

        /// <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);
            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;
        }

        [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 _repository.AddRangeAsync(newAttachment);
            await _repository.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 _repository.AddAsync(newAttachment);
            var success = await _repository.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).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());
        }

        /// <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);
        }


    }
}
