using Elasticsearch.Net;
using JiaZhiQuan.Common.ElasticSearch;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP.Containers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Cache;
using Wicture.DbRESTFul.Infrastructure.Repository;

namespace JiaZhiQuan.Common
{
    public static partial class RepositoryExtension
    {


        /// <summary>
        /// 检查拉黑情况
        /// 如果用户主动拉黑，则 返回 您已拉黑此用户，无法进行此操作
        /// 如果被其他用户拉黑，则 返回 由于用户隐私设置，无法进行此操作
        /// 如果正常，则返回 null
        /// </summary>
        public async static Task<string> CheckInBlacklist(this DbRESTFulRepository repository, long userId, IList<long> blackUserIds, IDbConnection conn = null, string errorMessage = "无法进行此操作")
        {
            var query = new { userId, blackUserIds };
            var id = await repository.QuerySingleOrDefaultAsync<int>("select id from n_user_blacklist where userId=@userId and blackUserId in @blackUserIds limit 1", query, conn);
            if (id > 0)
            {
                throw new LogicalException($"您已拉黑此用户，{errorMessage}");
            }
            id = await repository.QuerySingleOrDefaultAsync<int>("select id from n_user_blacklist where blackUserId=@userId and userId in @blackUserIds limit 1", query, conn);
            if (id > 0)
            {
                throw new LogicalException($"由于对方隐私设置，{errorMessage}");
            }
            return null;
        }

        /// <summary>
        /// 获取当前用户的黑名单
        /// </summary>
        public async static Task<List<long>> GetBlackUserIdList(this DbRESTFulRepository repository, long userId = 0, IDbConnection conn = null)
        {
            if (userId == 0)
            {
                userId = long.Parse(repository.Context?.Identity?.Id ?? "0");
            }
            if (userId > 0)
            {
                var list = (await repository.QueryAsync<dynamic>("select userId, blackUserId from n_user_blacklist where userId=@userId or blackUserId=@userId", new { userId }, conn)).ToList();
                var set = new HashSet<long>();
                list.ForEach(e =>
                {
                    if (e.userId != userId) set.Add(e.userId);
                    if (e.blackUserId != userId) set.Add(e.blackUserId);
                });
                return set.ToList();
            }
            return new List<long>();
        }

    }

}
