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

namespace GxPress.Service.Implement.IM
{
    /// <summary>
    /// 创建群组
    /// </summary>
    public partial class IMService
    {
        /// <summary>
        /// 创建群
        /// </summary>
        /// <returns></returns>
        public async Task<CreateGroupChatResult> CreateGroupChatAsync(GroupChatInRequest request)
        {
            var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
            var result = new CreateGroupChatResult();
            if (string.IsNullOrEmpty(request.Name))
                throw new BusinessException("群名称不能为空");
            if (string.IsNullOrEmpty(request.AvatarUrl))
                throw new BusinessException("群头像不能为空");
            if (string.IsNullOrEmpty(request.Introduce))
                throw new BusinessException("群介绍不能为空");
            try
            {
                var token = await _cache.GetAsync<string>("ImToken");
                //创建群
                var url = $"{imServiceUrl}/chatgroups";
                var headers = new Dictionary<string, string> { { "Authorization", "Bearer " + token } };
                // //获取成员
                var users = await _userRepository.UserListInsAsync(request.UserIds);
                //获取用户
                var user = await _userRepository.GetAsync(request.UserId);
                // var list = new List<string>();
                // list.AddRange(users.Select(n => n.ImId));
                // //构造数据
                // string userValues = string.Empty;
                // foreach (var value in list)
                //     userValues += "\"" + value + "\",";
                // if (userValues.Length > 0)
                //     userValues = userValues.Remove(userValues.Length - 1, 1);
                var members_only = request.IsAdmin ? "true" : "false";
                var jsonString =
                    "{\"groupname\":\"" + request.Name + "\",\"desc\":\"" + request.Introduce +
                    "\",\"public\":true,\"maxusers\":1000,\"members_only\":" + members_only + ",\"owner\":\"" +
                    user.ImId + "\",\"members\":[]}";
                var response =
                    await HttpClientHelper.PostAsync(url, JsonConvert.DeserializeObject(jsonString), headers);
                var tokenJson = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    result.Success = true;
                    var dataJsonDynamic = JsonConvert.DeserializeObject<dynamic>(tokenJson);
                    //获取groupChatImId
                    request.GroupChatImId = dataJsonDynamic.data.groupid.ToString();
                    result.GroupChatImId = request.GroupChatImId;
                    //创建群写入数据库
                    request.UserIds = new List<int>();
                   
                    await _groupChatRepository.InsertAsync(request);
                    return result;
                }
                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("接口被限流");
                result.Success = false;
            }
            catch (Exception e)
            {
                throw new BusinessException(e.Message);
            }

            return result;
        }

    }
}
