package edge_service

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"iot_manager_service/config"
	"net/http"
	url2 "net/url"
)

type RecordAlarmRecord struct{}

type RecordAlarmRecordRes struct {
	Code int                     `json:"code"`
	Msg  string                  `json:"msg"`
	Data []RecordAlarmRecordData `json:"data"`
}

type RecordAlarmRecordData struct {
	ID        int    `json:"id"`
	Code      string `json:"code"`
	Tstart    string `json:"tstart"`
	Tend      string `json:"tend"`
	Content   string `json:"content"`
	Alarmtype int    `json:"alarmtype"`
	Level     int    `json:"level"`
	Threshold int    `json:"threshold"`
	Value     int    `json:"value"`
	Sid       int    `json:"sid"`
	Cid       int    `json:"cid"`
	Cname     string `json:"cname"`
	Updatedat string `json:"updatedat"`
}

// SyncAlartRecord  同步报警 数据
func (r *RecordAlarmRecord) SyncAlartRecord(maxId int64, maxUpDateTime string) ([]RecordAlarmRecordData, error) {
	maxId += 1
	cfg := config.Instance()
	api := cfg.Foreign.IotEdgeUrl + "/data/v1/alarm/sync"
	url := fmt.Sprintf("%v?id=%d&&updatedat=%v", api, maxId, url2.QueryEscape(maxUpDateTime))
	fmt.Printf("url = %v", url)
	method := "GET"
	client := &http.Client{}
	req, err := http.NewRequest(method, url, nil)

	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 := RecordAlarmRecordRes{}
	err = json.Unmarshal(body, &result)
	if err != nil {
		return nil, err
	}
	if result.Code != 0 {
		panic(result.Msg)
	}
	//fmt.Printf("result.Data = %v", result.Data)
	return result.Data, nil
}
