package restapi

import (
	"encoding/json"
	"fmt"

	"git.wecise.com/wecise/common/rest"
)

func Request(method, url, body string) (map[string]any, error) {
	var fm *rest.ReqForm = &rest.ReqForm{
		Username:    "wecise.admin",
		Password:    "admin",
		Timeout:     60, // 整个请求的超时时间，秒（包含连接、写入、读取）
		Body:        body,
		ContentType: "application/json;charset=UTF-8",
		Transport:   nil,
	}
	b, err := rest.Request(method, url, fm)
	if err != nil {
		return nil, fmt.Errorf("request %s %s error: %v", url, method, err)
	}
	res := make(map[string]any)
	if b[0] == '{' {
		if err = json.Unmarshal(b, &res); err != nil {
			return nil, fmt.Errorf("unmarshal response json error: %v", err)
		}
		switch res["status"].(type) {
		case string:
			if res["status"] != "ok" {
				return nil, fmt.Errorf("%s %s response status error: \n%s", url, method, string(b))
			}
		default:
		}
	} else {
		return nil, fmt.Errorf("%s %s response error: %s", url, method, string(b))
	}
	return res, nil
}
