package backend

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
)

const UnifiedLandingPlatform = "https://api.user.1688sup.com"

func MenusList(c *gin.Context) {
	// Target URL
	baseURL := UnifiedLandingPlatform + "/v1/menu/myCodes?systemId="
	// Construct the complete target URL, including the path and query parameters
	request := c.Query("systemId")
	if request == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数解析失败"})
		return
	}
	baseURL += request
	// Rebuild the request
	req, err := http.NewRequest(c.Request.Method, baseURL, bytes.NewBufferString(request))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "构建请求失败"})
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header = c.Request.Header
	// Initiate the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "请求失败"})
		return
	}
	defer resp.Body.Close()
	// Copy the response content to the original request's response
	for k, v := range resp.Header {
		for _, value := range v {
			c.Header(k, value)
		}
	}
	data, _ := io.ReadAll(resp.Body)
	_, err = c.Writer.Write(data)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "写入数据失败"})
		return
	}
	return
}