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

namespace YBDevice.WX.DBServices
{
    /// <summary>
    /// 微信开放平台openticket配置
    /// </summary>
    public class OpenWXConfigApp : Repository<YB_OpenWXConfig>
    {
        /// <summary>
        /// 增加或者更新openticket
        /// </summary>
        /// <param name="model"></param>
        public async Task InsertOrUpdateAsync(YB_OpenWXConfig model)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                try
                {
                    if (await dbClient.Queryable<YB_OpenWXConfig>().AnyAsync(x => x.ComponentAppId == model.ComponentAppId))
                    {
                        await dbClient.Updateable<YB_OpenWXConfig>().SetColumns(x => new YB_OpenWXConfig
                        {
                            OpenTicket = model.OpenTicket
                        }).Where(x => x.ComponentAppId == model.ComponentAppId).ExecuteCommandAsync();
                    }
                    else
                    {
                       await dbClient.Insertable<YB_OpenWXConfig>(model).ExecuteCommandAsync();
                    }
                }
                catch (Exception ex)
                {
                    var errmsg = $"{model.ToJson()}";
                    new LoggerApp().InsertErrorLog(ex, errmsg, "更新ticket");
                }
            }
        }

        /// <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;
            }
        }
    }
}
