using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GxPress.Common.Exceptions;
using GxPress.Entity.Topic;
using GxPress.EnumConst;
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> UpdateAsync(TopicUpdateRequest request)
        {
            var topic = await _topicRepository.GetAsync(request.Id);
            if (request.UserId != topic.UserId)
                throw new BusinessException("话题不属于该用户");
            if (!string.IsNullOrEmpty(request.Title))
                topic.Title = request.Title;
            if (!string.IsNullOrEmpty(request.Content))
            {
                topic.TextContent = string.Empty;
                topic.Content = request.Content;
                topic.HtmlContent = request.HtmlContent;
                var contentJsonData = JsonConvert.DeserializeObject<List<ContentJsonData>>(request.Content);
                foreach (var data in contentJsonData)
                {
                    if (data.Type == AllTypeConst.Text.GetHashCode())
                        topic.TextContent += data.Text;
                }
            }
            else
            {
                topic.TextContent = "[]";
                topic.Content = string.Empty;
                topic.HtmlContent = string.Empty;
            }
            //是否草稿
            topic.IsDraft = request.IsDraft;
            return await _topicRepository.UpdateAsync(topic);
        }
    }
}