package xiaoice

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/errorx"
	"io"
	"net/http"
	"net/url"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *SignatureGenLogic) SignatureGen() (resp *types.SignatureResp, err error) {
	// 构建请求URL
	key := l.svcCtx.Config.Xiaoice.SubscriptionKey
	baseURL, err := url.Parse("https://interactive-virtualhuman.xiaoice.com/openapi/signature/gen")
	if err != nil {
		return nil, err
	}

	// 在这里设置请求参数
	//params := url.Values{}
	// 如果需要设置 token 有效期，请取消下面注释并设置时间（以毫秒为单位）
	//params.Add("effectiveDurationMilliseconds", strconv.Itoa(24*60*60*1000))
	//baseURL.RawQuery = params.Encode()

	// 创建 HTTP 请求
	req, err := http.NewRequest("GET", baseURL.String(), nil)
	if err != nil {
		return nil, err
	}

	// 添加必要的Header信息
	req.Header.Add("subscription-key", key)

	// 创建HTTP客户端并执行请求
	client := &http.Client{}
	response, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			l.Error("获取小冰 AuthToken 失败: %v", err)
		}
	}(response.Body)

	// 读取和输出响应
	body, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	// 检查响应状态
	if response.StatusCode != http.StatusOK {
		//log.Fatalf("请求失败，状态码：%d，响应: %s", response.StatusCode, string(body))
		return nil, errorx.NewDefaultError(fmt.Sprintf("获取小冰 AuthToken 失败：%d，响应: %s", response.StatusCode, string(body)))
	}

	// 解析 JSON 响应
	var responseMap types.XiaoiceSignatureResp
	if err := json.Unmarshal(body, &responseMap); err != nil {
		return nil, err
	}

	fmt.Printf("响应: %s\n", string(body))
	return &types.SignatureResp{Data: &responseMap.Data}, nil
}
