package fastgpt

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"io/ioutil"
	"net/http"
	"strconv"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
)

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

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

func (l *GetAppsListLogic) GetAppsList(req *types.AppsListReq) (resp *types.AppsListResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	organizationIdStr := strconv.FormatUint(organizationId, 10)
	token, err := GetToken(organizationIdStr)
	if err != nil {
		return nil, fmt.Errorf("invalid token")
	}

	keyword := ""
	if req.Keyword != nil {
		keyword = *req.Keyword
	}
	response := CoreAppList(req.Type, keyword, token)

	return &types.AppsListResp{Data: response}, nil
}

// 定义一个结构体用于表示整个 JSON 响应
type Response struct {
	Status string                    `json:"status"`
	Data   []*types.AppsListRespInfo `json:"data"`
}

type AppListRequest struct {
	Type      []string `json:"type"`
	SearchKey string   `json:"searchKey"`
}

func CoreAppList(apps_type string, searchKey string, token string) []*types.AppsListRespInfo {
	url := "https://fastgpt.gkscrm.com/api/core/app/list"
	requestBodyData := AppListRequest{
		Type:      []string{"folder", apps_type},
		SearchKey: searchKey,
	}

	// 将结构体转换为 JSON 字节切片
	requestBody, err := json.Marshal(requestBodyData)
	if err != nil {
		fmt.Printf("Error marshalling request body: %v\n", err)
		return nil
	}

	// 创建一个新的请求
	req1, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return nil
	}

	// 设置请求头
	req1.Header.Set("Content-Type", "application/json")
	req1.Header.Set("Cookie", fmt.Sprintf("fastgpt_token=%s", token))

	// 使用 http.Client 发送请求
	client := &http.Client{}
	resp1, err := client.Do(req1)
	if err != nil {
		fmt.Printf("Error sending request: %v\n", err)
		return nil
	}
	defer resp1.Body.Close()

	// 读取响应
	body, err := ioutil.ReadAll(resp1.Body)
	if err != nil {
		fmt.Printf("Error reading response: %v\n", err)
		return nil
	}

	var response Response
	err = json.Unmarshal(body, &response)
	if err != nil {
		fmt.Printf("Error unmarshalling JSON: %v\n", err)
		return nil
	}
	return response.Data
}
