using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Hosting;
using QuestionSwapDoc;
using QuestionSwapDoc.SwapWordModel;
using YGNT.QuestionLibrary.Core.Disciplines.Cache;
using YGNT.QuestionLibrary.Core.Helper;
using YGNT.QuestionLibrary.Core.Models;
using YGNT.QuestionLibrary.Core.Questions.Cache;

namespace YGNT.QuestionLibrary.Core.Questions.Domain
{
    public class QuestionOriginManager : IQuestionOriginManager
    {
        private readonly IRepository<Resolve, long> _resolveRepository;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly IDisciplineQuestionTypeCache _disciplineQuestionTypeCache;
        private readonly IQuestionTypeCache _questionTypeCache;
        private readonly IRepository<QuestionOrigin, long> _questionOriginRepository;

        public QuestionOriginManager(IRepository<Resolve, long> resolveRepository, IWebHostEnvironment webHostEnvironment, IDisciplineQuestionTypeCache disciplineQuestionTypeCache, IQuestionTypeCache questionTypeCache, IRepository<QuestionOrigin, long> questionOriginRepository)
        {
            _resolveRepository = resolveRepository;
            _webHostEnvironment = webHostEnvironment;
            _disciplineQuestionTypeCache = disciplineQuestionTypeCache;
            _questionTypeCache = questionTypeCache;
            _questionOriginRepository = questionOriginRepository;
        }

        /// <summary>
        /// 重新生成试题文档
        /// </summary>
        /// <param name="question"></param>
        /// <returns></returns>
        public void ProduceDoc(Question question)
        {
            if (question.QuestionOrigin == null)
                question.QuestionOrigin = _questionOriginRepository.FirstOrDefault(
                    x => x.Id == question.QuestionOriginId);
            var resolves = _resolveRepository.GetAll()
                .Where(x => x.QuestionOriginId == question.QuestionOrigin.Id)
                .ToList();
            var disciplineQuestionType = _disciplineQuestionTypeCache.Get(question.DisciplineQuestionTypeId);
            var questionType = _questionTypeCache.Get(question.QuestionTypeId);
            var queItem = new SwapWordJoinQueItem()
            {
                TiXinStr = disciplineQuestionType.Name,
                ImgLinkLeftPath = _webHostEnvironment.WebRootPath,
                IsXuanZhe = questionType.Name == "单选题" || questionType.Name == "多选题",
                IsPanDuan = questionType.Name == "判断题"
            };
            var fullResolve = new Resolve()
            {
                QuestionOriginId = question.QuestionOriginId,
                ResolveType = ResolveType.完整试题
            };
            foreach (var resolve in resolves)
            {
                switch (resolve.ResolveType)
                {
                    case ResolveType.题干和选项:
                        queItem.TiRange = GetSwapQueContent(resolve);
                        break;
                    case ResolveType.答案:
                        queItem.DaAnRange = GetSwapQueContent(resolve);
                        break;
                    case ResolveType.解析:
                        queItem.JieXiRange = GetSwapQueContent(resolve);
                        break;
                    case ResolveType.完整试题:
                        fullResolve = resolve;
                        break;
                }
            }

            var dir = Path.GetDirectoryName(queItem.TiRange.XmlFile);
            var newFilePath = Path.Combine(dir, Path.ChangeExtension(Path.GetRandomFileName(), Path.GetExtension(queItem.TiRange.XmlFile)));
            SwapWord.JoinQue(newFilePath, queItem);
            if (!System.IO.File.Exists(newFilePath))
                throw new UserFriendlyException("重新生成试题文档失败");
            var oldXml = _webHostEnvironment.SplicePath(fullResolve.XmlPath);
            fullResolve.XmlPath = Path.GetRelativePath(_webHostEnvironment.WebRootPath, newFilePath);
            _resolveRepository.InsertOrUpdate(fullResolve);
            if (System.IO.File.Exists(oldXml))
                System.IO.File.Delete(oldXml);
        }

        private SwapQueContent GetSwapQueContent(Resolve resolve)
        {
            return new SwapQueContent()
            {
                HtmlText = resolve.Html,
                XmlFile = _webHostEnvironment.SplicePath(resolve.XmlPath)
            };
        }

        /// <summary>
        /// 重新生成试题结构Html
        /// </summary>
        /// <param name="resolve"></param>
        /// <returns></returns>
        public void ReProduceDoc(Resolve resolve)
        {
            var dir = Path.GetDirectoryName(resolve.XmlPath);
            var newFilePath = Path.Combine(_webHostEnvironment.WebRootPath, dir, Path.GetRandomFileName());
            SwapWord.HtmlToWord(newFilePath,
                resolve.Html.Replace(QuestionLibraryConsts.ResolveImgPlaceholder, string.Empty),
                _webHostEnvironment.WebRootPath);
            if (!System.IO.File.Exists(newFilePath))
                throw new UserFriendlyException("重新生成试题结构失败");
            resolve.XmlPath = Path.GetRelativePath(_webHostEnvironment.WebRootPath, newFilePath);
            _resolveRepository.Update(resolve);
        }
    }
}