using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using GxPress.Common.Exceptions;
using GxPress.Common.Http;
using GxPress.Request.App.IM;
using Newtonsoft.Json;
using GxPress.Common.Extensions;
using GxPress.Common.Tools;

namespace GxPress.Service.Implement.IM
{
    public partial class IMService
    {
        /// <summary>
        /// 群添加成员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> InsertGroupChatUsersAsync(InsertGroupChatUsersRequest request)
        {
            var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
            var token = await _cache.GetAsync<string>("ImToken");
            //创建群
            var url = $"{imServiceUrl}/chatgroups/{request.GroupChatImId}/users";
            var headers = new Dictionary<string, string> { { "Authorization", "Bearer " + token } };
            //获取成员
            var users = await _userRepository.UserListInsAsync(request.UserIds);
            request.Users = users.ToList();
            if (request.Users.Count == 0)
                return false;
            var usersObj = new { usernames = users.Select(n => n.ImId) };
            var response =
                await HttpClientHelper.PostAsync(url, usersObj, headers);
            var tokenJson = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
                var dataJsonDynamic = JsonConvert.DeserializeObject<dynamic>(tokenJson);
                request.GroupChatImId = dataJsonDynamic.data.groupid.ToString();
                return await groupChatService.InsertUsersIntoGroupChatAsync(request);
            }
            //
            if (!string.IsNullOrWhiteSpace(request.GroupChatImId) && request.IsFound)
            {
                var groupChat = await _groupChatRepository.GetGroupChatByImIdAsync(request.GroupChatImId);
                await groupChatService.DeleteAsync(groupChat.Id);
            }
            if (response.StatusCode == HttpStatusCode.NotFound)
                throw new BusinessException("此群组ID或被添加的人不存在");
            if (response.StatusCode == HttpStatusCode.Unauthorized)
                throw new BusinessException("未授权[无token、token错误、token过期]");
            if (response.StatusCode == HttpStatusCode.BadRequest)
                throw new BusinessException("owner用户不存在");
            if (response.StatusCode == HttpStatusCode.TooManyRequests)
                throw new BusinessException("接口被限流");
            return false;
        }
    }
}
