using Hotline.Share.Dtos.Snapshot;
using Hotline.Users;
using Microsoft.Extensions.Logging;
using Senparc.CO2NET.Extensions;
using Senparc.Weixin;
using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
using Senparc.Weixin.WxOpen.AdvancedAPIs.WxApp;
using Senparc.Weixin.WxOpen.Containers;
using XF.Domain.Exceptions;

namespace Hotline.WeChat;

public class WeChatService : IThirdIdentiyService
{
    private readonly ILogger<WeChatService> _logger;

    public WeChatService(ILogger<WeChatService> logger)
    {
        _logger = logger;
    }

    public async Task<ThirdTokenOutDto> GetTokenAsync(ThirdTokenDto dto)
    {
        try
        {
            var result = await SnsApi.JsCode2JsonAsync(dto.AppId, dto.Secret, dto.LoginCode);
            if (result.errcode != ReturnCode.请求成功) throw UserFriendlyException.SameMessage("获取微信用户信息失败");
            return new ThirdTokenOutDto() { SessionKey = result.session_key, OpenId = result.openid };

        }
        catch (Exception e)
        {
            _logger.LogError("微信登录失败:" + e.Message + "\r\n" + e.StackTrace);
            throw UserFriendlyException.SameMessage("微信登录失败:" + e.Message);
        }
    }

    /// <summary>
    /// 获取手机号码
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<ThirdPhoneOutDto> GetPhoneNumberAsync(ThirdTokenDto dto)
    {
        await AccessTokenContainer.RegisterAsync(dto.AppId, dto.Secret);
        _logger.LogInformation($"GetPhoneNumberAsync: {dto.ToJson()}");
        var result = await BusinessApi.GetUserPhoneNumberAsync(dto.AppId, dto.TelCode);
        if (result.errcode != ReturnCode.请求成功)
            _logger.LogError($"GetPhoneNumberAsync: {result.ToJson()}");
        return new ThirdPhoneOutDto()
        {
            ErrorCode = (int)result.errcode,
            IsError = result.errcode != ReturnCode.请求成功,
            ErrorMessage = result.errmsg + " " + result.errcode,
            PhoneNumber = result.phone_info?.phoneNumber
        };
    }
}
