package edge_service

import (
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"io/ioutil"
	"iot_manager_service/config"
	"iot_manager_service/util/logger"
	"net/http"
	"strings"
)

// CltLedControlService led 显示屏 请求边缘云端接口
type CltLedControlService struct{}

type CltLedControlReqPost struct {
	Codes []string    `json:"codes"`
	Param interface{} `json:"param"`
}
type CltLedControlReq struct {
	Tenant   string `json:"tenant"`
	Action   string `json:"action"`
	PostData CltLedControlReqPost
}

type CltLedControlRes struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func (f CltLedControlService) RequestApi(reqData CltLedControlReq) {
	cfg := config.Instance()
	reqId := uuid.New().String()
	url := fmt.Sprintf("%v/cltled/v1/%v/%v/%v", cfg.Foreign.IotEdgeUrl, reqData.Tenant, reqData.Action, reqId)

	method := "POST"

	client := &http.Client{}
	marshal, _ := json.Marshal(reqData.PostData)
	fmt.Printf("playJson = %v \n", string(marshal))

	req, err := http.NewRequest(method, url, strings.NewReader(string(marshal)))
	if err != nil {
		logger.Logger.Errorf("CltLedControlService NewRequest %v", err.Error())
		return
	}
	req.Header.Add("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		logger.Logger.Errorf("CltLedControlService Do %v", err.Error())
		return
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		logger.Logger.Errorf("CltLedControlService ReadAll %v", err.Error())
		return
	}
	var cltLedControlRes CltLedControlRes
	err = json.Unmarshal(body, &cltLedControlRes)
	if err != nil {
		logger.Logger.Errorf("CltLedControlService Unmarshal %v", err.Error())
		return
	}
	if cltLedControlRes.Code != 0 {
		fmt.Printf("RequestApi url = %v \n", url)
		fmt.Printf("reqData = %v \n", reqData)
		logger.Logger.Errorf("CltLedControlService cltLedControlRes %v", cltLedControlRes.Msg)
		return
	}
	return
}
