using Aliyun.OSS;
using Elasticsearch.Net;
using JiaZhiQuan.Common.AliOSS;
using JiaZhiQuan.Common.Config;
using JiaZhiQuan.Common.ElasticSearch;
using JiaZhiQuan.Common.ElasticSearch.Models;
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>
        /// 检查是否需要给用户发放笔记价值币
        /// </summary>
        public static async Task<bool> CheckShouldPostPointsGiven(this DbRESTFulRepository repository, long userId, ConfigFromDb dbConfig, IDbConnection conn = null)
        {
            if (CommonUtils.IsMockUser(userId) || dbConfig.UserPointsPublishPost < 1) return false;
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            return (await repository.QuerySingleOrDefaultAsync<int>($"select count(id) from n_user_points_record where userId={userId} and way='POST' and createAtDate='{date}'", null, conn)) < dbConfig.UserPointsPublishPostMaxCount;
        }

        /// <summary>
        /// 检查是否需要给用户发放评论价值币
        /// </summary>
        public static async Task<bool> CheckShouldCommentPointsGiven(this DbRESTFulRepository repository, long userId, ConfigFromDb dbConfig, IDbConnection conn = null)
        {
            if (CommonUtils.IsMockUser(userId) || dbConfig.UserPointsComment < 1) return false;
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            return (await repository.QuerySingleOrDefaultAsync<int>($"select count(id) from n_user_points_record where userId={userId} and way='COMMENT' and createAtDate='{date}'", null, conn)) < dbConfig.UserPointsCommentMaxCount;
        }

        public static async Task<bool> GivenPoints(this DbRESTFulRepository repository, long userId, ConfigFromDb config, IDbConnection conn)
        {
            if (await repository.CheckShouldCommentPointsGiven(userId, config, conn))
            {
                var trans = conn.BeginTransaction();
                try
                {
                    await repository.QueryAsync<dynamic>("insert into n_user_points_record(userId, points, way, description, createAt, createAtDate) values (@userId, @points, 'COMMENT', @description, @now, @now)", new { userId, points = config.UserPointsComment, description = "发表评论，欧拉币奖励", now = DateTime.Now }, conn, trans);
                    await repository.QueryAsync<dynamic>("update n_user_statistic set points=points+@points where userId=@userId", new { points = config.UserPointsComment, userId }, conn, trans);
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    LoggerManager.Logger.Error(ex, "赠送欧拉币失败" + "\r\n" + ex.Message);
                }
                return true;
            }
            return false;
        }
    }

}
