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);
                    //创建话题管理员
                    var topicAddressee = new TopicAddressee
                    {
                        IsAdmin = true,
                        IsRead = true,
                        TopicId = topicId,
                        UserId = request.UserId,
                        IsUpload = false
                    };
                    //获取用用户
                    var user = await _userRepository.GetAsync(request.UserId);
                    topicAddressee.UserName = user.Name;
                    await _topicAddresseeRepository.InsertAsync(topicAddressee);
                    //获取小组成员
                    if (request.GroupId > 0)
                    {
                        var groupUsers =
                            await _groupUserRepository.GetAllAsync(Q.Where(nameof(GroupUser.GroupId), request.GroupId));
                        request.TopicAddresseeUserIds = groupUsers.Select(n => n.UserId).ToList();
                    }
                    //获取共享文件夹成员
                    if (request.FolderId > 0)
                    {
                        var middle = await _middleRepository.GetMiddleAsync(request.FolderId);
                        if (middle.AttributeValue == 2 && middle.RoleId == 1)
                        {
                            var users = await _userRepository.GetAllAsync(Q.Where(nameof(Entity.User.Id), ">", 0));
                            request.TopicAddresseeUserIds = users.Select(n => n.Id).ToList();
                        }
                        else
                        {
                            var folderUsers = await _folderUserRepository.GetAllAsync(request.FolderId);
                            request.TopicAddresseeUserIds = folderUsers.Select(n => n.UserId).ToList();
                        }
                        //另存为笔记
                        var noteRequest = new NoteInRequest
                        {
                            Title = request.Title,
                            Content = request.Content,
                            UserId = request.UserId,
                            FolderId = request.FolderId,
                            HtmlContent = request.HtmlContent

                        };
                        await _noteService.InsertNoteAsync(noteRequest);
                        //设置默认共享文件夹
                        await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.IsDefault), false).Where(nameof(Entity.Middle.Middle.UserId), request.UserId).WhereIn(nameof(Entity.Middle.Middle.RoleId), new List<int> { 1, 3 }));
                        //修改默认
                        await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.IsDefault), true).Where(nameof(Entity.Middle.Middle.Id), request.FolderId));
                    }
                    var topicAddressees = new List<TopicAddressee>();
                    //
                    request.TopicAddresseeUserIds.Add(request.UserId);
                    //创建话题讨论成员
                    foreach (var item in request.TopicAddresseeUserIds)
                    {
                        if (item == request.UserId)
                            continue;
                        //创建话题管理员
                        topicAddressee = new TopicAddressee
                        {
                            TopicId = topicId,
                            UserId = item
                        };
                        topicAddressees.Add(topicAddressee);
                    }
                    //添加话题阅读成员
                    await _topicAddresseeRepository.InsertAsync(topicAddressees);
                    //修改话题访问量
                    await _visitService.AddVisit(request.UserId, 2, topicId);
                    transactionScope.Complete();
                }
            }
            catch (Exception e)
            {
                throw new BusinessException(e.Message);
            }

            return true;
        }
    }
}
