package utils

import (
	"github.com/medivhzhan/weapp/v3"
	"github.com/medivhzhan/weapp/v3/auth"
	"github.com/medivhzhan/weapp/v3/phonenumber"
	"go.uber.org/zap"
	"miniapp/global"
	"miniapp/model/app/request"
)

type wechat struct{}

func WeChatUtils() *wechat {
	return &wechat{}
}

// GetWechatUnionId 获取微信用户基础信息
func (w wechat) GetWechatUnionId(code string) (unionId, openId, sessionKey string, err error) {
	sdk := weapp.NewClient(global.GVA_CONFIG.MiniApp.AppId, global.GVA_CONFIG.MiniApp.AppSecret, weapp.WithLogger(nil))
	cli := sdk.NewAuth()

	p := auth.Code2SessionRequest{
		Appid:     global.GVA_CONFIG.MiniApp.AppId,
		Secret:    global.GVA_CONFIG.MiniApp.AppSecret,
		JsCode:    code,
		GrantType: "authorization_code",
	}

	session, err := cli.Code2Session(&p)
	if err != nil {
		return
	}
	if session.GetResponseError() != nil {
		global.GVA_LOG.Error("Code解析失败: %v", zap.Error(session.GetResponseError()))
		err = session.GetResponseError()
		return
	}
	// 设置UnionId值
	unionId = session.Unionid
	openId = session.Openid
	sessionKey = session.SessionKey
	return
}

// GetWechatPhone 根据Code获取小程序用户手机号
// return 不带区号的手机号
func (w wechat) GetWechatPhone(param request.DecryptMobile) (string, error) {
	sdk := weapp.NewClient(global.GVA_CONFIG.MiniApp.AppId, global.GVA_CONFIG.MiniApp.AppSecret)
	mobile, err := sdk.DecryptMobile(param.SessionKey, param.EncryptedData, param.Iv)
	if err != nil {
		global.GVA_LOG.Error("解密手机号失败: %v", zap.Error(err))
		return "", err
	}
	global.GVA_LOG.Debug("解密后的手机号: %+v", zap.String("mobile", mobile.PurePhoneNumber))
	return mobile.PurePhoneNumber, nil
}

// GetPhoneNumber 获取手机号
func (w wechat) GetPhoneNumber(code string) (phone string, err error) {
	sdk := weapp.NewClient(global.GVA_CONFIG.MiniApp.AppId, global.GVA_CONFIG.MiniApp.AppSecret)
	resp, err := sdk.NewPhonenumber().GetPhoneNumber(&phonenumber.GetPhoneNumberRequest{Code: code})
	if err != nil {
		global.GVA_LOG.Error("获取手机号失败: %v", zap.Error(err))
		return
	}
	// 获取手机号
	phone = resp.Data.PurePhoneNumber
	return
}
