using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GxPress.Common.Exceptions;
using GxPress.Entity.Topic;
using GxPress.Request.App.Topic;

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.Content = request.Content;
                topic.HtmlContent = request.HtmlContent;
            }
            //获取共享文件夹成员
            if (request.FolderId > 0)
            {
                var folderUsers = await _folderUserRepository.GetAllAsync(request.FolderId);
                request.TopicAddresseeUserIds = folderUsers.Select(n => n.UserId).ToList();
                //删除topicAddress
                await _topicAddresseeRepository.DeletByTopicIdAsync(request.Id);
                topic.FolderId = request.FolderId;
            }
            var topicAddressees = new List<TopicAddressee>();
            //
            request.TopicAddresseeUserIds.Add(request.UserId);
            //创建话题讨论成员
            foreach (var item in request.TopicAddresseeUserIds)
            {
                //创建话题管理员
                var topicAddressee = new TopicAddressee
                {
                    TopicId = request.Id,
                    UserId = item,
                    IsAdmin = item == request.UserId
                };
                topicAddressees.Add(topicAddressee);
            }
            //添加话题阅读成员
            await _topicAddresseeRepository.InsertAsync(topicAddressees);
            return await _topicRepository.UpdateAsync(topic);
        }
    }
}