package api

import (
	"encoding/json"
	"fmt"
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/utility/serializer"
	"github.com/gin-gonic/gin"
	"gopkg.in/go-playground/validator.v8"
	"io/ioutil"
	"net/http"
	"os"
)

func Ping(c *gin.Context) {
	c.JSON(200, serializer.Response{
		Code: 0,
		Msg:  "Pong",
	})
}

func JsonResource(c *gin.Context) {
	var (
		req     forms.JsonResource
		jsonMap []map[string]interface{}
		URL     = os.Getenv("ADMIN_JSON_RESOURCE_URL")
	)

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, serializer.ParamErr(err.Error(), nil))
		return
	}

	URL = URL + req.Version + "/" + req.Name
	resp, err := http.Get(URL)
	if err != nil {
		c.JSON(200, serializer.ParamErr(err.Error(), nil))
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		c.JSON(200, serializer.ParamErr(err.Error(), nil))
		return
	}

	if err = json.Unmarshal(body, &jsonMap); err != nil {
		c.JSON(200, serializer.ParamErr(err.Error(), nil))
		return
	}
	c.JSON(200, jsonMap)
}

func ErrorResponse(err error) serializer.Response {
	if ve, ok := err.(validator.ValidationErrors); ok {
		for _, e := range ve {
			field := config.T(fmt.Sprintf("Field.%s", e.Field))
			tag := config.T(fmt.Sprintf("Tag.Valid.%s", e.Tag))
			return serializer.ParamErr(
				fmt.Sprintf("%s%s", field, tag),
				err,
			)
		}
	}
	if _, ok := err.(*json.UnmarshalTypeError); ok {
		return serializer.ParamErr("JSON类型不匹配", err)
	}

	return serializer.ParamErr("参数错误", err)
}
