using IRaCIS.Application.Interfaces;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Infra.EFCore;
using Microsoft.AspNetCore.Mvc;
using Panda.DynamicWebApi.Attributes;

namespace IRaCIS.Application.Services
{
    [ ApiExplorerSettings(GroupName = "Reviewer")]
    public class VacationService : BaseService, IVacationService
    {
        private readonly IRepository<Vacation> _vacationRepository;

        public VacationService(IRepository<Vacation> vacationRepository)
        {
            _vacationRepository = vacationRepository;
        }
        /// <summary>
        /// 添加休假时间段
        /// </summary>
        /// <param name="param">Status不传</param>
        /// <returns></returns>

        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateVacation(VacationCommand param)
        {
            if (param.Id == Guid.Empty|| param.Id ==null)
            {
                var result = await _vacationRepository.AddAsync(_mapper.Map<Vacation>(param));

                var success = await _repository.SaveChangesAsync();

                return ResponseOutput.Result(success, result.Id);

            }
            else
            {
                var success = await _vacationRepository.BatchUpdateNoTrackingAsync(u => u.Id == param.Id,
                h => new Vacation
                {
                    StartDate = param.StartDate,
                    EndDate = param.EndDate
                });

                return ResponseOutput.Result(success);

            }

        }
        /// <summary>
        /// 删除休假时间段
        /// </summary>
        /// <param name="holidayId">记录Id</param>
        /// <returns></returns>
       
        [HttpDelete("{holidayId:guid}")]
        public async Task<IResponseOutput> DeleteVacation(Guid holidayId)
        {
            var success = await _vacationRepository.BatchDeleteNoTrackingAsync(u => u.Id == holidayId);

            return ResponseOutput.Result(success);

        }

        /// <summary>
        /// 获取休假时间段列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("{doctorId:guid}/{pageIndex:int}/{pageSize:int}")]
        public async Task<PageOutput<VacationCommand>> GetVacationList(Guid doctorId, int pageIndex, int pageSize)
        {
            var query = _vacationRepository.Where(u => u.DoctorId == doctorId)
                .ProjectTo<VacationCommand>(_mapper.ConfigurationProvider);

            return await query.ToPagedListAsync(pageIndex, pageSize, "StartDate");
       
        }

        [NonDynamicMethod]
        public async Task<IResponseOutput> OnVacation(Guid doctorId)
        {
            var count = await _vacationRepository.CountAsync(u => u.DoctorId == doctorId && u.EndDate >= DateTime.Now && u.StartDate <= DateTime.Now);

            return ResponseOutput.Result(count > 0);
        }

    }
}
