package edge_service

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

type RecordAlarmSos struct{}

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

type RecordAlarmSosData struct {
	ID        int     `json:"id"`
	Code      string  `json:"code"`
	Tstart    string  `json:"tstart"`
	Tend      string  `json:"tend"`
	Duration  float64 `json:"duration"`
	Updatedat string  `json:"updatedat"`
}

// SyncRecord 同步sos一键求助数据
func (r *RecordAlarmSos) SyncRecord(maxId int64, maxUpDateTime string) ([]RecordAlarmSosData, error) {
	cfg := config.Instance()
	api := cfg.Foreign.IotEdgeUrl + "/data/v1/sos/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 := RecordAlarmSosReq{}
	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
}
