package wxcard

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"
	"wechat-api/hook/wechat"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/ArtisanCloud/PowerWeChat/v2/src/kernel/power"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetApiWxCardQrcodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetApiWxCardQrcodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApiWxCardQrcodeLogic {
	return &GetApiWxCardQrcodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetApiWxCardQrcodeLogic) GetApiWxCardQrcode(req *types.QrcodeReq, w http.ResponseWriter) {
	AppId := l.svcCtx.Config.Miniprogram.Appid
	Secret := l.svcCtx.Config.Miniprogram.Secret

	// 1. 初始化小程序应用实例
	app, err := wechat.NewClient(AppId, Secret)
	if err != nil {
		fmt.Printf("init wechat miniprogram failed:%v\n", err)
		return
	}

	// Urldecode 操作
	rawPath, _ := url.QueryUnescape(req.Path)

	// 从解析后的URL里获取信息
	parser, _ := url.Parse(rawPath)
	//fmt.Printf("path=%v, query_string=%v\n", parser.Path, parser.RawQuery)

	scene, path := parser.RawQuery, parser.Path
	if scene == "" {
		scene = "share"
	}

	pphash := power.HashMap{}
	resp, err := app.WXACode.GetUnlimited(
		scene,
		path,
		false,
		req.EnvVersion,
		req.Width,
		false,
		&pphash,
		false,
	)
	if err != nil {
		fmt.Printf("get miniprogram qrcode failed:%v\n", err)
		return
	}
	defer resp.Body.Close()

	imageContent, _ := io.ReadAll(resp.Body)
	w.Header().Set("Content-Type", "image/png")
	w.Header().Set("Content-Length", strconv.Itoa(len(imageContent)))
	nbytes, err := w.Write(imageContent)
	fmt.Printf("nbytes=%d err=%v\n", nbytes, err)
}
