using Hncore.Infrastructure.Service;
using Hncore.Pass.Vpn.Domain;
using Hncore.Wx.Open;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace Hncore.Pass.Vpn.Service
{

    public partial class WxAppService : ServiceBase<WxAppEntity>
    {
        public WxAppService(CourseContext dbContext, IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
        {

        }

        public async Task SaveAppInfo(GetAuthorizerInfoResponse info, int tenantId, int storeId)
        {
            var wxAppInfo = await this.Query(true).FirstOrDefaultAsync(m => m.TenantId == tenantId
            && m.Appid == info.authorization_info.authorizer_appid
            && m.DeleteTag == 0);

            var wxAuthInfoNew = new WxAppEntity()
            {
                TenantId = tenantId,
                StoreId = storeId,
                Appid = info.authorization_info.authorizer_appid,
                HeadImg = info.authorizer_info.head_img,
                NickName = info.authorizer_info.nick_name,
                PrincipalName = info.authorizer_info.principal_name,
                UserName = info.authorizer_info.user_name,
                Bussinessinfo = info.authorizer_info.signature,
                AuthorizerState = 0,
                RefreshToken = info.authorization_info.authorizer_refresh_token,
                ExpiresIn = info.authorization_info.expires_in,
            };
            if (wxAppInfo == null)
            {
                await this.Add(wxAuthInfoNew);
            }
            else
            {
                wxAuthInfoNew.Id = wxAppInfo.Id;
                await this.Update(wxAuthInfoNew);
            }
        }
    }
}