using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Datory;
using GxPress.Common.Exceptions;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.Entity.Topic;
using GxPress.Request.App.Note;
using GxPress.Request.App.Topic;
using GxPress.Result;
using Newtonsoft.Json;

namespace GxPress.Service.Implement.Topic
{
    public partial class TopicService
    {

        /// <summary>
        /// 创建话题
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> InsertTopicAsync(TopicInRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.Title) && string.IsNullOrWhiteSpace(request.HtmlContent))
                throw new BusinessException("标题和内容必填一项!");
            try
            {
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    //创建话题
                    var topic = new Entity.Topic.Topic
                    {
                        UserId = request.UserId,
                        Content = request.Content,
                        HtmlContent = request.HtmlContent,
                        Title = request.Title,
                        GroupId = request.GroupId,
                        FolderId = request.FolderId
                    };

                    if (!string.IsNullOrEmpty(request.Content))
                    {
                        var contentJsonData = JsonConvert.DeserializeObject<List<ContentJsonData>>(request.Content);
                        foreach (var item in contentJsonData)
                        {
                            item.File = StringUtils.RemoveDomain(item.File);
                        }
                        topic.Content = JsonConvert.SerializeObject(contentJsonData);
                    }
                    var topicId = await _topicRepository.InsertAsync(topic);
                    //修改话题访问量
                    await _visitService.AddVisit(request.UserId, GxPress.EnumConst.AllTypeConst.Topic.GetHashCode(), topicId);
                    transactionScope.Complete();
                }
            }
            catch (Exception e)
            {
                throw new BusinessException(e.Message);
            }

            return true;
        }
    }
}