using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using GxPress.Common.Exceptions;
using GxPress.Common.Http;
using GxPress.Common.Extensions;
using GxPress.Common.Tools;

namespace GxPress.Service.Implement.IM
{
    /// <summary>
    /// 解散群组
    /// </summary>
    public partial class IMService
    {
        /// <summary>
        /// 根据ImId删除群组
        /// </summary>
        /// <param name="groupChatImId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteGroupChatAsync(string groupChatImId,int userId)
        {
             var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
            //获取群信息
            var groupChat = await _groupChatRepository.GetGroupChatByImIdAsync(groupChatImId);
            if (groupChat == null)
                throw new BusinessException("群不存在");
            if(groupChat.UserId!=userId)
                throw new BusinessException("不是群主不能解散群");
            var url = $"{imServiceUrl}/chatgroups/{groupChatImId}";
            try
            {
                var token = await _cache.GetAsync<string>("ImToken");
                var headers = new Dictionary<string, string> { { "Authorization", "Bearer " + token } };
                var response =
                   await HttpClientHelper.DeleteAsync(url, headers);
                var tokenJson = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    //删除群 
                    await _groupChatRepository.DeleteAsync(groupChat.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("接口被限流");

            }
            catch (System.Exception ex)
            {
                throw new BusinessException(ex.Message);
            }
            return true;
        }
    }
}