package consumer

import (
	"encoding/json"
	"fmt"
	"git.quantgroup.cn/DevOps/enoch/service/data"
	"git.quantgroup.cn/DevOps/enoch/service/file_cache"
	"git.quantgroup.cn/DevOps/enoch/service/log"
	"github.com/influxdata/influxdb/client/v2"
)

func batchWrite(pointArray []*client.Point) {
	if file_cache.Enabled() {
		logger.Info.Println("写入缓存")
		fileWrite(pointArray)
	} else {
		err := httpWrite(pointArray)
		if err != nil {
			file_cache.OpenCache()
			fileWrite(pointArray)
		}
		logger.Info.Println("写入influx", len(pointArray))
	}
}

func httpWrite(pointArray []*client.Point) error {
	c := data.NewClient()
	defer func() { _ = c.Close() }()

	points, err := client.NewBatchPoints(client.BatchPointsConfig{
		Database: "monitor",
		//Precision : "ms",
	})
	if err != nil {
		return err
	}

	points.AddPoints(pointArray)
	err = c.Write(points)
	if err != nil {
		return err
	}
	return nil
}
func ReSubmit(data []string) error {
	pointSlice := make([]*client.Point, 0)
	for _, v := range data {
		cp := file_cache.CreateCachePoint(v)
		point, err := client.NewPoint(cp.Name, cp.Tags, cp.Fields, cp.Time)
		if err != nil {
			logger.Error.Println("构造client.point异常", err)
		}
		pointSlice = append(pointSlice, point)
		if len(pointSlice) > 1000 {
			err := httpWrite(pointSlice)
			if err != nil {
				return err
			}
			logger.Info.Println("缓存重新提交：1000")
			pointSlice = make([]*client.Point, 0)
		}
	}
	if len(pointSlice) > 0 {
		err := httpWrite(pointSlice)
		if err != nil {
			logger.Info.Println(pointSlice)
			return err
		}
		logger.Info.Println("缓存重新提交：", len(pointSlice))
	}
	logger.Info.Println("重新提交")
	return nil
}

func fileWrite(pointArray []*client.Point) {
	for _, p := range pointArray {
		if p != nil {
			current := file_cache.NewPoint(p)
			data, err := json.Marshal(current)
			if err != nil {
				fmt.Println(err)
			}
			file_cache.Write(string(data))
		}
	}
}

