using Nirvana.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.Service.DBServices
{
    /// <summary>
    /// 微信开放平台openticket配置
    /// </summary>
    public partial class OpenWXConfigApp : Repository<YB_OpenWXConfig>
    {
        /// <summary>
        /// 获取openticket
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <returns></returns>
        public static async Task<string> GetOpenTicketAsync(string componentAppId)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                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)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                try
                {
                    var data = await dbClient.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}";
                    new LoggerApp().InsertErrorLog(ex, errmsg, "获取公众号的刷新token");
                    return "";
                }
            }
        }
    }
}
