package wechat

import (
	"errors"
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/miniprogram"
	"github.com/silenceper/wechat/v2/miniprogram/auth"
	"github.com/silenceper/wechat/v2/miniprogram/config"
	"github.com/silenceper/wechat/v2/miniprogram/encryptor"
)

type miniProgram struct {
	Memory *cache.Memory
	Config *config.Config
	weixin *wechat.Wechat //微信登录实例
	*miniprogram.MiniProgram
}

var MiniProgram = miniProgram{}

// Init 初始化
func (that *miniProgram) Init(appid string, appsecret string) {

	that.weixin = wechat.NewWechat()
	that.Memory = cache.NewMemory()
	that.Config = &config.Config{
		AppID:     appid,
		AppSecret: appsecret,
		//Token:     "xxx",
		//EncodingAESKey: "xxxx",
		Cache: that.Memory,
	}
	that.MiniProgram = that.weixin.GetMiniProgram(that.Config)
}

func (that *miniProgram) GetBaseUserInfo(code string) (appid string, re auth.ResCode2Session, err error) {
	appid = that.Config.AppID
	a := that.GetAuth()
	re, err = a.Code2Session(code)

	if err != nil {
		return appid, re, err
	}

	return appid, re, err
}

func (that *miniProgram) GetPhoneNumber(sessionkey, encryptedData, iv string) (appid string, re *encryptor.PlainData, err error) {
	appid = that.Config.AppID

	if sessionkey == "" || encryptedData == "" || iv == "" {
		return appid, re, errors.New("参数不足")
	}

	eny := that.GetEncryptor()

	re, err = eny.Decrypt(sessionkey, encryptedData, iv)

	if err != nil {
		return appid, re, err
	}

	return appid, re, err

}
