package fastgpt

import (
	"bytes"
	"context"
	"fmt"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"net/http"
	"strconv"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *CreateAppLogic) CreateApp(req *types.CreateAppsReq) (resp *types.BaseMsgResp, 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")
	}

	AppCreate(req.Type, req.Name, token)

	return &types.BaseMsgResp{Msg: errormsg.Success}, nil
}

func AppCreate(apps_type string, name string, token string) {
	url := "https://fastgpt.gkscrm.com/api/core/app/create"

	jsonData := ""
	if apps_type == "simple" {
		jsonData = fmt.Sprintf(`{"parentId":"","avatar":"core/app/type/simpleFill","name":"%s","type":"simple","modules":[{"nodeId":"userGuide","name":"common:core.module.template.system_config","intro":"common:core.module.template.config_params","avatar":"core/workflow/template/systemConfig","flowNodeType":"userGuide","position":{"x":531.2422736065552,"y":-486.7611729549753},"version":"481","inputs":[{"key":"welcomeText","renderTypeList":["hidden"],"valueType":"string","label":"core.app.Welcome Text","value":""},{"key":"variables","renderTypeList":["hidden"],"valueType":"any","label":"core.app.Chat Variable","value":[]},{"key":"questionGuide","valueType":"object","renderTypeList":["hidden"],"label":"core.app.Question Guide","value":{"open":false}},{"key":"tts","renderTypeList":["hidden"],"valueType":"any","label":"","value":{"type":"web"}},{"key":"whisper","renderTypeList":["hidden"],"valueType":"any","label":"","value":{"open":false,"autoSend":false,"autoTTSResponse":false}},{"key":"scheduleTrigger","renderTypeList":["hidden"],"valueType":"any","label":"","value":null}],"outputs":[]},{"nodeId":"448745","name":"common:core.module.template.work_start","intro":"","avatar":"core/workflow/template/workflowStart","flowNodeType":"workflowStart","position":{"x":558.4082376415505,"y":123.72387429194112},"version":"481","inputs":[{"key":"userChatInput","renderTypeList":["reference","textarea"],"valueType":"string","label":"common:core.module.input.label.user question","required":true,"toolDescription":"common:core.module.input.label.user question"}],"outputs":[{"id":"userChatInput","key":"userChatInput","label":"core.module.input.label.user question","valueType":"string","type":"static"}]},{"nodeId":"loOvhld2ZTKa","name":"common:core.module.template.ai_chat","intro":"common:core.module.template.ai_chat_intro","avatar":"core/workflow/template/aiChat","flowNodeType":"chatNode","showStatus":true,"position":{"x":1097.7317280958762,"y":-244.16014496351386},"version":"481","inputs":[{"key":"model","renderTypeList":["settingLLMModel","reference"],"label":"core.module.input.label.aiModel","valueType":"string","value":"gpt-4o-mini"},{"key":"temperature","renderTypeList":["hidden"],"label":"","value":0,"valueType":"number","min":0,"max":10,"step":1},{"key":"maxToken","renderTypeList":["hidden"],"label":"","value":2000,"valueType":"number","min":100,"max":4000,"step":50},{"key":"isResponseAnswerText","renderTypeList":["hidden"],"label":"","value":true,"valueType":"boolean"},{"key":"quoteTemplate","renderTypeList":["hidden"],"label":"","valueType":"string"},{"key":"quotePrompt","renderTypeList":["hidden"],"label":"","valueType":"string"},{"key":"systemPrompt","renderTypeList":["textarea","reference"],"max":3000,"valueType":"string","label":"core.ai.Prompt","description":"core.app.tip.systemPromptTip","placeholder":"core.app.tip.chatNodeSystemPromptTip","value":""},{"key":"history","renderTypeList":["numberInput","reference"],"valueType":"chatHistory","label":"core.module.input.label.chat history","required":true,"min":0,"max":30,"value":6},{"key":"userChatInput","renderTypeList":["reference","textarea"],"valueType":"string","label":"common:core.module.input.label.user question","required":true,"toolDescription":"common:core.module.input.label.user question","value":["448745","userChatInput"]},{"key":"quoteQA","renderTypeList":["settingDatasetQuotePrompt"],"label":"","debugLabel":"common:core.module.Dataset quote.label","description":"","valueType":"datasetQuote"}],"outputs":[{"id":"history","key":"history","label":"core.module.output.label.New context","description":"core.module.output.description.New context","valueType":"chatHistory","type":"static"},{"id":"answerText","key":"answerText","label":"core.module.output.label.Ai response content","description":"core.module.output.description.Ai response content","valueType":"string","type":"static"}]}],"edges":[{"source":"448745","target":"loOvhld2ZTKa","sourceHandle":"448745-source-right","targetHandle":"loOvhld2ZTKa-target-left"}]}`, name)
	} else {
		jsonData = fmt.Sprintf(`{"parentId":"","avatar":"core/app/type/workflowFill","name":"%s","type":"advanced","modules":[{"nodeId":"userGuide","name":"common:core.module.template.system_config","intro":"common:core.module.template.system_config_info","avatar":"core/workflow/template/systemConfig","flowNodeType":"userGuide","position":{"x":262.2732338817093,"y":-476.00241136598146},"version":"481","inputs":[{"key":"welcomeText","renderTypeList":["hidden"],"valueType":"string","label":"core.app.Welcome Text","value":""},{"key":"variables","renderTypeList":["hidden"],"valueType":"any","label":"core.app.Chat Variable","value":[]},{"key":"questionGuide","valueType":"any","renderTypeList":["hidden"],"label":"core.app.Question Guide","value":{"open":false}},{"key":"tts","renderTypeList":["hidden"],"valueType":"any","label":"","value":{"type":"web"}},{"key":"whisper","renderTypeList":["hidden"],"valueType":"any","label":"","value":{"open":false,"autoSend":false,"autoTTSResponse":false}},{"key":"scheduleTrigger","renderTypeList":["hidden"],"valueType":"any","label":"","value":null}],"outputs":[]},{"nodeId":"448745","name":"common:core.module.template.work_start","intro":"","avatar":"core/workflow/template/workflowStart","flowNodeType":"workflowStart","position":{"x":632.368838596004,"y":-347.7446492944009},"version":"481","inputs":[{"key":"userChatInput","renderTypeList":["reference","textarea"],"valueType":"string","label":"common:core.module.input.label.user question","required":true,"toolDescription":"common:core.module.input.label.user question"}],"outputs":[{"id":"userChatInput","key":"userChatInput","label":"common:core.module.input.label.user question","type":"static","valueType":"string"}]}],"edges":[]}`, name)
	}
	requestBody := []byte(jsonData)
	// 创建一个新的请求
	req1, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return
	}

	// 设置请求头
	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)
	logx.Info("AppCreate resp1:", resp1)
	logx.Info("AppCreate err:", err)
	if err != nil {
		fmt.Printf("Error sending request: %v\n", err)
		return
	}
	defer resp1.Body.Close()

	return
}
