package edge_service

import (
	"encoding/json"
	"fmt"
	"github.com/mitchellh/mapstructure"
	"io/ioutil"
	"iot_manager_service/config"
	"net/http"
	"strings"
)

// ForLightRate 获取设备能耗数据
type ForLightRate struct{}

// ForLightRateReq 请求参数
type ForLightRateReq struct {
	Tenant string `json:"tenant"` //租户号
	Start  string `json:"start"`
	End    string `json:"end"`
	Flag   int    `json:"flag"` //0日 1月 2季 3年
}

// ForLightRateRes 返回数据
type ForLightRateRes struct {
	Code int                    `json:"code"`
	Msg  string                 `json:"msg"`
	Data map[string]interface{} `json:"data"`
}
type ForLightRateData struct {
	Date   string  `json:"date"`
	Month  string  `json:"month"`
	Total  int     `json:"total"`
	Number int     `json:"number"`
	Rate   float64 `json:"rate"`
}

func (r *ForLightRate) GetLightRate(reqPostData ForLightRateReq) ([]ForLightRateData, error) {
	//if reqPostData.Tenant == "100000" {
	//	reqPostData.Tenant = "000000"
	//}
	cfg := config.Instance()
	api := cfg.Foreign.IotEdgeUrl + "/data/v1/lightingrate"
	method := "POST"
	client := &http.Client{}
	marshal, _ := json.Marshal(reqPostData)
	req, err := http.NewRequest(method, api, strings.NewReader(string(marshal)))

	if err != nil {
		return nil, err
	}
	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	//fmt.Printf("body = %v", string(body))
	result := ForLightRateRes{}
	err = json.Unmarshal(body, &result)
	if err != nil {
		return nil, err
	}
	if result.Code != 0 {
		panic(result.Msg)
	}
	data := result.Data
	var list []ForLightRateData
	err = mapstructure.Decode(data["data"], &list)
	if err != nil {
		return nil, err
	}
	println(data["data"])
	fmt.Printf("list = %v \n", list)
	return list, nil
}
