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

namespace IRaCIS.Core.Application.Service
{
    [ApiExplorerSettings(GroupName = "Reviewer")]
    public class VacationService(IRepository<Vacation> _vacationRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IVacationService
    {

        /// <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 _vacationRepository.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(new PageInput() { PageIndex = pageIndex, PageSize = pageSize }, nameof(VacationCommand.StartDate));

        }

        [NonDynamicMethod]
        public async Task<IResponseOutput> OnVacation(Guid doctorId)
        {
            //防止生成sql生成GETDATE() 时区导致的问题
            var appDateTimeNow = DateTime.Now;

            var count = await _vacationRepository.CountAsync(u => u.DoctorId == doctorId && u.EndDate >= appDateTimeNow && u.StartDate <= appDateTimeNow);

            return ResponseOutput.Result(count > 0);
        }

    }
}
