using Hotline.Settings;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Share.Tools;
using Hotline.ThirdAccountDomainServices.Interfaces;
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.Dependency;
using XF.Domain.Exceptions;

namespace Hotline.WeChat;

public class WeChatService : IThirdIdentiyService, IScopeDependency
{
    private readonly ILogger<WeChatService> _logger;
    private readonly ISystemLogRepository _systemLog;

    public WeChatService(ILogger<WeChatService> logger, ISystemLogRepository systemLog)
    {
        _logger = logger;
        _systemLog = systemLog;
    }

    public async Task<ThirdTokenOutDto> GetTokenAsync(ThirdTokenDto dto, CancellationToken token)
    {
        try
        {
            GetWebApiHost(dto.WebApiHost);
            var result = await SnsApi.JsCode2JsonAsync(dto.AppId, dto.Secret, dto.LoginCode);
            _systemLog.Add("微信获取Token", dto, status: 1, executeResult: result.ToJson());
            if (result.errcode != ReturnCode.请求成功) throw UserFriendlyException.SameMessage("获取微信用户信息失败");
            return new ThirdTokenOutDto() { SessionKey = result.session_key, OpenId = result.openid , UnIonId = result.unionid};

        }
        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, CancellationToken token)
    {
        GetWebApiHost(dto.WebApiHost);
        await AccessTokenContainer.RegisterAsync(dto.AppId, dto.Secret);
        _logger.LogInformation($"GetPhoneNumberAsync: {dto.ToJson()}");
        var result = await BusinessApi.GetUserPhoneNumberAsync(dto.AppId, dto.TelCode);
        _systemLog.Add("微信获取手机号码", dto, status: 1, executeResult: result.ToJson());
        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,
        };
    }

    private void GetWebApiHost(string? webApiHost)
    {
        if (webApiHost.NotNullOrEmpty())
            Config.ApiMpHost = webApiHost;
    }
}
