using Furion.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Core;
using YBDevice.Entity;

namespace YBDevice.Application.WXConfig
{
    public class WXConfigService : IWXConfigService, ITransient
    {
        private readonly ISqlSugarRepository<YB_OpenWXConfig> repository;
        private readonly SqlSugarClient dbClient;
        private readonly ILoggerService _loggerService;

        public WXConfigService(ISqlSugarRepository<YB_OpenWXConfig> sqlSugarRepository, ILoggerService loggerService)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
            _loggerService = loggerService;
        }
        /// <summary>
        /// 获取openticket
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <returns></returns>
        public async Task<string> GetOpenTicketAsync(string componentAppId)
        {
            var component = await dbClient.Queryable<YB_OpenWXConfig>().Where(x => x.ComponentAppId == componentAppId).FirstAsync();
            return component?.OpenTicket;
        }

        /// <summary>
        /// 获取公众号的刷新token
        /// </summary>
        /// <param name="authorizerId">公众号appid</param>
        /// <param name="componentAppId">开放平台appid</param>
        /// <returns></returns>
        public async Task<string> GetRefreshToken(string authorizerId, string componentAppId)
        {
            try
            {
                var data = await repository.Change<YB_OfficlaAccount>().Context.Queryable<YB_OfficlaAccount>().FirstAsync(x => x.authorizer_appid == authorizerId && x.componentappid == componentAppId);
                if (data != null)
                {
                    return data.authorizer_refresh_token;
                }
                return "";
            }
            catch (Exception ex)
            {
                var errmsg = $"authorizerid={authorizerId},componentAppid={componentAppId}";
                _loggerService.AddErrorLogger(ex, errmsg, "获取公众号的刷新token");
                return "";
            }
        }
    }
}
