package edge_service

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

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

// CaptureItsReq 请求参数
type ForCaptureItsReq struct {
	Codes []string `json:"codes"` //抓拍单元 capture_sn列表
	Types []int    `json:"types"` //vtype 车型
	Start string   `json:"start"`
	End   string   `json:"end"`
	Flag  int      `json:"flag"` //0按日 1按月
}

// ForCaptureItsRes 返回数据
type ForCaptureItsRes struct {
	Code int                 `json:"code"`
	Msg  string              `json:"msg"`
	Data []ForCaptureItsData `json:"data"`
}
type ForCaptureItsData struct {
	Code  string `json:"code"`  //抓拍单元 capture_sn
	Time  string `json:"time"`  //时间 2022-05-01  ||2022-05
	Flag  int    `json:"flag"`  //0:日数据，1：月数据，2:小时数据
	Sflag int    `json:"sflag"` //车速区间时：
	Total int    `json:"total"` //数量

	Province string `json:"province"` //归属地时-用到的省
	City     string `json:"city"`     //归属地时-用到的城市

	Vtype int    `json:"vtype"` //车型统计
	Plate string `json:"plate"` //车牌记录-车牌
	Speed int    `json:"speed"` //车牌记录-车速
}

// VehicleTotal 统计日 月 车流量 数据
func (f ForCaptureIts) VehicleTotal(reqPostData ForCaptureItsReq) ([]ForCaptureItsData, error) {
	api := "/data/v1/its/vehicletotal"
	return f.pubPost(reqPostData, api)
}

// Province 归属地省统计
func (f ForCaptureIts) Province(reqPostData ForCaptureItsReq) ([]ForCaptureItsData, error) {
	api := "/data/v1/its/province"
	return f.pubPost(reqPostData, api)
}

// City 归属地城市统计
func (f ForCaptureIts) City(reqPostData ForCaptureItsReq) ([]ForCaptureItsData, error) {
	api := "/data/v1/its/provincecity"
	return f.pubPost(reqPostData, api)
}

// Vehicletypeex 车型统计
func (f ForCaptureIts) Vehicletypeex(reqPostData ForCaptureItsReq) ([]ForCaptureItsData, error) {
	api := "/data/v1/its/vehicletypeex"
	return f.pubPost(reqPostData, api)
}

// Vehiclespeedtotal 车速区间统计 日月
func (f ForCaptureIts) VehicleSpeedTotal(reqPostData ForCaptureItsReq) ([]ForCaptureItsData, error) {
	api := "/data/v1/its/vehiclespeedtotal"
	return f.pubPost(reqPostData, api)
}

// Vehicleoverspeedtotal 车速超速区间统计
func (f ForCaptureIts) VehicleOverSpeedTotal(reqPostData ForCaptureItsReq) ([]ForCaptureItsData, error) {
	api := "/data/v1/its/vehicleoverspeedtotal"
	return f.pubPost(reqPostData, api)
}

// VehicleHourTotal 小时统计数据
func (f ForCaptureIts) VehicleHourTotal(reqPostData ForCaptureItsReq) ([]ForCaptureItsData, error) {
	api := "/data/v1/its/vehiclehourtotal"
	return f.pubPost(reqPostData, api)
}

// Vehicleplate 同步车牌记录
func (f ForCaptureIts) Vehicleplate(reqPostData ForCaptureItsReq) ([]ForCaptureItsData, error) {
	api := "/data/v1/its/vehicleplate"
	return f.pubPost(reqPostData, api)
}

//公用 post请求
func (f ForCaptureIts) pubPost(reqPostData ForCaptureItsReq, api string) ([]ForCaptureItsData, error) {
	cfg := config.Instance()
	api = cfg.Foreign.IotEdgeUrl + api
	//fmt.Printf("api = %v \n", api)
	if !strings.Contains(reqPostData.Start, ":") {
		reqPostData.Start = reqPostData.Start + " 00:00:00"
		reqPostData.End = reqPostData.End + " 23:59:59"
	}
	//fmt.Printf("reqPostData = %v \n", reqPostData)
	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 := ForCaptureItsRes{}
	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
}

// SyncOverSpeedRecordData 同步超速车牌数据结构
type SyncOverSpeedRecordData struct {
	ID    int    `json:"id"`
	Code  string `json:"code"`
	Time  string `json:"time"`
	Vtype int    `json:"vtype"`
	Plate string `json:"plate"`
	Speed int    `json:"speed"`
	Flag  int    `json:"flag"`
}

//同步超速车牌号返回数据
type syncOverSpeedRecordDataRes struct {
	Code int                       `json:"code"`
	Msg  string                    `json:"msg"`
	Data []SyncOverSpeedRecordData `json:"data"`
}

func (r *ForCaptureIts) SyncOverSpeedRecord(maxId int64, maxUpDateTime string, start, end string) ([]SyncOverSpeedRecordData, error) {
	maxId += 1
	if maxUpDateTime == "" {
		maxUpDateTime = time.Now().AddDate(-1, 0, 0).Format("2006-01-02 15:04:05")
	}
	cfg := config.Instance()
	api := cfg.Foreign.IotEdgeUrl + "/data/v1/its/overspeed/sync"
	url := fmt.Sprintf("%v?id=%d&start=%v&end=%v", api, maxId, url2.QueryEscape(maxUpDateTime), url2.QueryEscape(time.Now().Format("2006-01-02 15:04:05")))
	if start != "" {
		parse, err := time.Parse("2006-01-02", start)
		if err != nil {
			parse = time.Now().AddDate(-1, 0, 0)
		}
		startStr := parse.Format("2006-01-02 15:04:05")
		url = fmt.Sprintf("%v?id=%d&start=%v&end=%v", api, maxId, url2.QueryEscape(startStr), url2.QueryEscape(time.Now().Format("2006-01-02 15:04:05")))
	}
	//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 := syncOverSpeedRecordDataRes{}
	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
}
