using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.Runtime.Session;
using Abp.UI;
using Mapster;
using YGNT.Infrastructure.Extension;
using YGNT.QuestionLibrary.Core.Tasks;
using YGNT.QuestionLibrary.Core.Tasks.Enum;
using YGNT.QuestionLibrary.Tasks.Dto.PaperProduce;

namespace YGNT.QuestionLibrary.Tasks
{
    public class PaperProduceTaskAppService : ApplicationService, IPaperProduceTaskAppService
    {
        private readonly IRepository<PaperProduceTask, long> _paperProduceTaskRepository;

        public PaperProduceTaskAppService(IRepository<PaperProduceTask, long> paperProduceTaskRepository)
        {
            _paperProduceTaskRepository = paperProduceTaskRepository;
        }

        /// <summary>
        /// 查询用户试卷生成任务列表
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<UserPaperProduceTaskDto>> GetListAsync(SearchPaperProduceTaskInputDto search)
        {
            var userId = AbpSession.GetUserId();
            var queryable = _paperProduceTaskRepository.GetAll()
                 .WhereIf(search.State.HasValue, x => x.TaskState == search.State)
                 .WhereIf(search.DisciplineId.HasValue, x => x.Paper.PaperDisciplines.Any(f => f.DisciplineId == search.DisciplineId))
                 .WhereIf(!search.KeyWord.IsNullOrEmpty(), x => x.Name.Contains(search.KeyWord))
                 .Where(x => x.UserId == userId)
                 .OrderBy(x => x.TaskState)
                 .ThenByDescending(x => x.CreationTime);
            var result = await queryable.GetResultAsync(search,
                x => x.Adapt(new UserPaperProduceTaskDto()
                {
                    Discipline = string.Join(",",
                        x.Paper.PaperDisciplines.Select(f => $"{f.Discipline.Grade.Name}-{f.Discipline.Name}"))
                }), default(long));
            return result;
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync([Required] long id)
        {
            var userId = AbpSession.GetUserId();
            var task = await _paperProduceTaskRepository.GetAsync(id);
            if (task.UserId != userId)
                throw new UserFriendlyException("禁止操作其他人的任务");
            if (task.TaskState == TaskState.正在执行)
                throw new UserFriendlyException("禁止删除正在执行的任务");
            await _paperProduceTaskRepository.DeleteAsync(task);
        }
    }
}