package services

import (
	"errors"
	"fmt"
	wechat "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"
	"github.com/silenceper/wechat/v2/miniprogram/qrcode"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/utils"
	"os"
	"time"
)

// 微信小程序配置信息
var (
	WxId        string //微信原始ID
	WxAppId     string
	WxAppSecret string
	WxPlatform  int    //用户来源，需要入库，用来保存该用户来自哪个平台，默认是：1
	EnvVersion  string // 小程序版本， release-正式版; trial-体验版; develop-开发版
)

func init() {
	WxAppId = `wxb059c872d79b9967`
	WxId = `gh_75abb562a946`
	WxAppSecret = `1737c73e9f69a21de1a345b8f0800258`
	WxPlatform = 6 //弘则研报来源
}

func GetWxApp() (miniprogram *miniprogram.MiniProgram) {
	wc := wechat.NewWechat()
	memory := cache.NewMemory()
	//memory := cache.NewRedis(global.Redis)
	cfg := &config.Config{
		AppID:     WxAppId,
		AppSecret: WxAppSecret,
		Cache:     memory,
	}

	miniprogram = wc.GetMiniProgram(cfg)
	return
}

// GetSession 获取用户详情
func GetSession(code string) (userInfo auth.ResCode2Session, err error) {
	wechatClient := GetWxApp()
	authClient := wechatClient.GetAuth()
	userInfo, err = authClient.Code2Session(code)
	return
}

// GetSession 获取用户详情
func GetUserInfo(code string) (userInfo auth.ResCode2Session, err error) {
	wechatClient := GetWxApp()
	authClient := wechatClient.GetAuth()
	fmt.Println("code:", code)
	userInfo, err = authClient.Code2Session(code)
	return
}

// 获取解密信息 GetDecryptInfo
func GetDecryptInfo(sessionKey, encryptedData, iv string) (decryptData *encryptor.PlainData, err error) {
	wechatClient := GetWxApp()
	encryptorClient := wechatClient.GetEncryptor()
	decryptData, err = encryptorClient.Decrypt(sessionKey, encryptedData, iv)
	return
}

// GetSunCode 获取太阳码
func GetSunCode(page, scene string) (resp []byte, err error) {
	// 此处因初始化顺序问题不放在init中
	env := "trial"
	if utils.RunMode == "release" {
		env = "release"
	}
	codePars := qrcode.QRCoder{
		Page:       page,
		Scene:      scene,
		EnvVersion: env,
	}
	wechatClient := GetWxApp()
	qr := wechatClient.GetQRCode()
	return qr.GetWXACodeUnlimit(codePars)
}

// PcCreateAndUploadSunCode 生成太阳码并上传OSS
func PcCreateAndUploadSunCode(scene, page string) (imgUrl string, err error) {
	if page == "" {
		err = errors.New("page不能为空")
		return
	}

	// scene超过32位会生成失败，md5处理至32位
	sceneMD5 := "a=1"
	if scene != "" {
		sceneMD5 = utils.MD5(scene)
	}
	picByte, err := GetSunCode(page, sceneMD5)
	if err != nil {
		return
	}
	// 生成图片
	localPath := "./static/imgs"
	fileName := utils.GetRandStringNoSpecialChar(28) + ".png"
	fpath := fmt.Sprint(localPath, "/", fileName)
	f, err := os.Create(fpath)
	if err != nil {
		fmt.Println("11111")
		return
	}
	if _, err = f.Write(picByte); err != nil {
		return
	}
	defer func() {
		f.Close()
		os.Remove(fpath)
	}()
	// 上传OSS
	fileDir := "yb/suncode/"
	imgUrl, err = UploadAliyunToDir(fileName, fpath, "", fileDir)
	if err != nil {
		return
	}

	if err != nil {
		return
	}
	// 记录参数
	if scene != "" {
		newSuncode := &models.YbPcSuncode{
			Scene:      scene,
			SceneMd5:   sceneMD5,
			CodePage:   page,
			SuncodeUrl: imgUrl,
			CreateTime: time.Now(),
		}
		err = models.AddYbPcSunCode(newSuncode)
	}
	// 记录参数md5
	if scene != "" {
		newPars := &models.YbSuncodePars{
			Scene:      scene,
			SceneKey:   sceneMD5,
			CreateTime: time.Now(),
		}
		err = models.AddYbSuncodePars(newPars)
	}
	return
}
