using System;
using System.Threading.Tasks;
using AutoMapper;
using Datory;
using GxPress.Common.Exceptions;
using GxPress.Common.Page;
using GxPress.Entity.WaitHandle;
using GxPress.Repository.Interface.WaitHandle;
using GxPress.Request.App.WaitHandle;
using GxPress.Result.App.WaitHandle;
using GxPress.Service.Interface.WaitHandle;

namespace GxPress.Service.Implement.WaitHandle
{
    public class WaitHandleService : IWaitHandleService
    {
        private readonly IWaitHandleRepository _waitHandleRepository;
        private readonly IWaitHandleLabelRepository _waitHandleLabelRepository;
        private readonly IMapper _mapper;
        public WaitHandleService(IWaitHandleLabelRepository waitHandleLabelRepository,
            IWaitHandleRepository waitHandleRepository, IMapper mapper)
        {
            _waitHandleLabelRepository = waitHandleLabelRepository;
            _waitHandleRepository = waitHandleRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加修改待办事项
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Entity.WaitHandle.WaitHandle> AddOrUpdateWaitHandleAsync(WaitHandleAddOrUpdateRequest request)
        {
            var id = 0;
            if (request.IsExecute)
            {
                if (string.IsNullOrEmpty(request.AlarmTime))
                    throw new BusinessException("时间未设置");
                var AlarmTime = DateTime.Parse(request.AlarmTime);
                if (AlarmTime <= DateTime.Now)
                    throw new BusinessException("时间小于当前时间");
                if (AlarmTime.AddMinutes(-request.Minute) <= DateTime.Now)
                    throw new BusinessException("提前提醒时间有误");
            }
            if (request.Id == 0)
            {
                var waitHandleMap = _mapper.Map<Entity.WaitHandle.WaitHandle>(request);
                if (string.IsNullOrEmpty(request.Title))
                    throw new BusinessException("标题为空");
                if (string.IsNullOrEmpty(request.Content))
                    throw new BusinessException("内容为空");
                waitHandleMap.IsFinish = false;
                if (request.Minute > 0)
                    waitHandleMap.Minute = request.Minute;
                else
                    waitHandleMap.Minute = 0;
                id = await _waitHandleRepository.InsertAsync(waitHandleMap);
                return await _waitHandleRepository.GetAsync(id);
            }
            var waitHandle = await _waitHandleRepository.GetAsync(request.Id);
            if (!string.IsNullOrEmpty(request.Title))
                waitHandle.Title = request.Title;
            if (!string.IsNullOrEmpty(request.Content))
                waitHandle.Content = request.Content;
            if (request.LabelId > 0)
                waitHandle.LabelId = request.LabelId;
            if (request.Minute > 0)
                waitHandle.Minute = request.Minute;
            if (request.Level > 0)
                waitHandle.Level = request.Level;
            waitHandle.AlarmTime = request.AlarmTime;
            if (request.IsExecute != waitHandle.IsExecute)
                waitHandle.IsExecute = request.IsExecute;
            await _waitHandleRepository.UpdateAsync(waitHandle);
            return await _waitHandleRepository.GetAsync(request.Id);
        }

        /// <summary>
        /// 删除待办事项
        /// </summary>
        /// <returns></returns>
        public async Task<bool> DeleteWaitHandleAsync(DeleteWaitHandleRequest request)
        {
            return await _waitHandleRepository.DeleteAsync(Q.WhereIn(nameof(Entity.WaitHandle.WaitHandle.Id), request.Ids));
        }

        /// <summary>
        /// // 待办搜索  Sort ：hand  手动 time按时间 label 标签 level 优先级
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<Entity.WaitHandle.WaitHandle>> PageWaitHandleAsync(PageWaitHandleRequest request)
        {
            var result = new PagedList<Entity.WaitHandle.WaitHandle>();
            var query = Q.NewQuery();
            query.Where(nameof(Entity.WaitHandle.WaitHandle.UserId), request.UserId);
            if (request.Sort == "hand")
                query.OrderByDesc(nameof(Entity.WaitHandle.WaitHandle.IsFinish));
            if (request.Sort == "time")
                query.OrderByDesc(nameof(Entity.WaitHandle.WaitHandle.AlarmTime));
            else if (request.Sort == "label")
            {
                query.OrderByDesc(nameof(Entity.WaitHandle.WaitHandle.LabelId));
            }
            else if (request.Sort == "level")
            {
                query.OrderByDesc(nameof(Entity.WaitHandle.WaitHandle.Level));
            }

            result.Total = await _waitHandleRepository.CountAsync(query);
            result.Items = await _waitHandleRepository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
            return result;
        }

        /// <summary>
        /// 添加修改标签
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> AddOrUpdateWaitHandleLabelAsync(WaitHandleLabelAddOrUpdateRequest request)
        {
            if (request.Id == 0)
            {
                var waitHandleLabel = new WaitHandleLabel { Title = request.Title, UserId = request.UserId };
                return await _waitHandleLabelRepository.InsertAsync(waitHandleLabel) > 0;
            }
            var waitHandleLabelDto = await _waitHandleLabelRepository.GetAsync(request.Id);
            if (!string.IsNullOrEmpty(request.Title))
                waitHandleLabelDto.Title = request.Title;
            return await _waitHandleLabelRepository.UpdateAsync(waitHandleLabelDto);
        }
        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> DeleteWaitHandleLabelAsync(DeleteWaitHandleRequest request)
        {
            return await _waitHandleLabelRepository.DeleteAsync(Q.WhereIn(nameof(WaitHandleLabel.Id), request.Ids));
        }


        /// <summary>
        /// // 待办搜索  Sort ：hand  手动 time按时间 label 标签 level 优先级
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<WaitHandleLabel>> PageWaitHandleLabelAsync(
            PageWaitHandleRequest request)
        {
            var result = new PagedList<WaitHandleLabel>();
            var query = Q.NewQuery();
            query.Where(nameof(WaitHandleLabel.UserId), request.UserId);
            result.Total = await _waitHandleLabelRepository.CountAsync(query);
            result.Items = await _waitHandleLabelRepository.GetAllAsync(query.OrderByDesc(nameof(WaitHandleLabel.CreatedDate)).ForPage(request.Page, request.PerPage));
            return result;
        }

        /// <summary>
        /// 待办搜索  1  手动 2 按时间 3 标签 4 优先级
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<WaitHandleListResult> WaitHandleListAsync(ListWaitHandleRequest request)
        {
            return await _waitHandleRepository.GetAllAsync(request);
        }

        /// <summary>
        /// 设置待办事项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> IsFinishAsync(int id)
        {
            var waitHandle = await _waitHandleRepository.GetAsync(id);
            if (waitHandle == null)
                throw new BusinessException("待办事项不存在");
            return await _waitHandleRepository.UpdateAsync(Q
                .Set(nameof(Entity.WaitHandle.WaitHandle.IsFinish), !waitHandle.IsFinish)
                .Where(nameof(Entity.WaitHandle.WaitHandle.Id), id));
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Entity.WaitHandle.WaitHandle> GetWaitAsync(int id)
        {
            return await _waitHandleRepository.GetWaitAsync(id);
        }
    }
}
