using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YGNT.Infrastructure.Extension;
using YGNT.Infrastructure.Helper;
using YGNT.Infrastructure.Model;
using YGNT.QuestionLibrary.Core.EducationCategories;
using YGNT.QuestionLibrary.Core.Grades;
using YGNT.QuestionLibrary.Core.IRepositories;
using YGNT.QuestionLibrary.Core.Permissions;
using YGNT.QuestionLibrary.EducationCategories;
using YGNT.QuestionLibrary.Grades.Dto;

namespace YGNT.QuestionLibrary.Grades
{
    /// <summary>
    /// 年级
    /// </summary>
    public class GradesAppService : IGradesAppService
    {
        private readonly IRepository<Grade> _gradeRepository;
        private readonly IHttpHelper _httpHelper;
        //private readonly IRepository<UserDiscipline, long> _userDisciplineRepository;
        //private readonly IGradeManager _gradeManager;
        private readonly IEducationCategoryAppService _educationCategoryAppService;

        public GradesAppService(IRepository<Grade> gradeRepository, IHttpHelper httpHelper, 
            IRepository<EducationCategory> educationCategoryRepository,
           IEducationCategoryAppService educationCategoryAppService)//, IGradeManager gradeManager)//, IRepository<UserDiscipline, long> userDisciplineRepository)
        {
            _gradeRepository = gradeRepository;
            _httpHelper = httpHelper;
            //_gradeManager = gradeManager;
            //_userDisciplineRepository = userDisciplineRepository;
            _educationCategoryAppService = educationCategoryAppService;
        }

        /// <summary>
        /// 查询年级列表
        /// </summary>
        public async Task<PagedResultDto<GradeDto>> GetListAsync(SearchGradeInputDto search)
        {
            var queryable = _gradeRepository.GetAll()
                .Where(x => x.EducationCategory.IsActive)
                .WhereIf(!search.KeyWord.IsNullOrEmpty(), x => x.Name.Contains(search.KeyWord))
                .WhereIf(search.EducationCategoryId.HasValue, x => x.EducationCategoryId == search.EducationCategoryId)
                .OrderBy(x => x.Name);
            return await queryable.GetResultAsync(search, x => x.Adapt(new GradeDto()
            {
                EducationCategoryName = x.EducationCategory.Name
            }));
        }

        /// <summary>
        /// 所有年级
        /// </summary>
        /// <returns></returns>
        public async Task<List<Grade>> GetListAll()
        {
            return await _gradeRepository.GetAll().ToListAsync();
        }

        /// <summary>
        /// 查询年级详情
        /// </summary>
        public async Task<GradeDto> GetOneAsync(int id)
        {
            var disciplineDto = await _gradeRepository.GetAll()
                .Where(x => x.Id == id)
                .Select(x => x.Adapt(new GradeDto()
                {
                    EducationCategoryName = x.EducationCategory.Name
                }))
                .FirstOrDefaultAsync();
            return disciplineDto;
        }

        /// <summary>
        /// 创建新年级
        /// </summary>
        [AbpAuthorize(QuestionLibraryAuthorizationProvider.GradePermissionName)]
        public async Task<int> CreateAsync(CreateGradeDto create)
        {
            var discipline = create.Adapt<Grade>();
            //await _gradeManager.CheckNameAsync(discipline.Name, discipline.EducationCategoryId);
            await _gradeRepository.InsertAndGetIdAsync(discipline);
            return discipline.Id;
        }

        /// <summary>
        /// 修改年级
        /// </summary>
        [AbpAuthorize(QuestionLibraryAuthorizationProvider.GradePermissionName)]
        public async Task UpdateAsync(int id, UpdateGradeDto update)
        {
            var discipline = await _gradeRepository.GetAsync(id);
            update.Adapt(discipline);
            //await _gradeManager.CheckNameAsync(discipline.Name, discipline.EducationCategoryId);
        }

        /// <summary>
        /// 删除年级
        /// </summary>
        [AbpAuthorize(QuestionLibraryAuthorizationProvider.GradePermissionName)]
        public async Task DeleteAsync(int id)
        {
            await _gradeRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 删除年级
        /// </summary>
        [AbpAuthorize(QuestionLibraryAuthorizationProvider.GradePermissionName)]
        public async Task DeleteListAsync(List<int> idList)
        {
            foreach (var id in idList)
            {
                await DeleteAsync(id);
            }
        }

        /// <summary>
        /// 同步年级
        /// </summary>
        /// <returns></returns>
        public async Task DataSyncAsync()
        {
            HttpResult httpResult = await _httpHelper.GetResponse($"{AppSettings.App("App", "ServerRoot")}/api/magic-api/educational/abutment/grade-info");
            if (httpResult.Success)
            {
                var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GradeSyncDto>>(httpResult.Data.ToString());
                var educationCategoryId = await _educationCategoryAppService.GetDefaultEducationCategory();

                foreach (var item in list)
                {
                    var isExist = await _gradeRepository.GetAll().AnyAsync(x => x.SourceId == item.Id);
                    if (isExist)
                    {
                        var grade = await _gradeRepository.FirstOrDefaultAsync(i => i.SourceId == item.Id);
                        grade.Name = item.Name;
                        grade.EducationCategoryId = educationCategoryId;
                        await _gradeRepository.UpdateAsync(grade);
                    }
                    else
                    {
                        var grade = new Grade { EducationCategoryId = educationCategoryId, Name = item.Name, SourceId = item.Id };

                        await _gradeRepository.InsertAndGetIdAsync(grade);

                    }
                }
            }
            else
            {
                throw new UserFriendlyException(httpResult.Message);
            }
        }

    }
}
