package service

import (
	commonConfig "cicv-data-closedloop/aarch64/pjisuv/common/config"
	"cicv-data-closedloop/aarch64/pjisuv/master/config"
	"cicv-data-closedloop/common/config/c_log"
	"cicv-data-closedloop/common/util"
	"cicv-data-closedloop/pjisuv_msgs"
	"fmt"
	"github.com/bluenviron/goroslib/v2"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"runtime"
	"time"
)

var (
	faultLogger *logrus.Logger
	logPath     string
	regularTime = 1 * time.Hour // 日志上传周期

)

func ForFaultCodeLog() {
	initLog("/mnt/media/sda1/cicv-data-closedloop/fault_code/", "fault_code")
	receiveFault()
	//uploadLodRegularly()
}

// InitLog 初始化日志配置
func initLog(logDir string, prefix string) {
	time.Sleep(time.Duration(1) * time.Second)
	// 创建、追加、读写，777，所有权限
	logPath = logDir + prefix + "-" + time.Now().Format("2006-01-02-15-04-05") + ".log"
	err := util.CreateParentDir(logPath)
	if err != nil {
		os.Exit(-1)
	}
	f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
	if err != nil {
		os.Exit(-1)
	}
	faultLogger = logrus.New()
	faultLogger.SetOutput(f)
	faultLogger.SetReportCaller(true) // 开启行号显示
	faultLogger.SetFormatter(&logrus.JSONFormatter{
		CallerPrettyfier: func(frame *runtime.Frame) (string, string) {
			fileName := filepath.Base(frame.File)
			return "", fmt.Sprintf("%s:%d", fileName, frame.Line)
		},
	})
	faultLogger.Info("初始化 faultLogger - 成功")
}

func receiveFault() {
	_, _ = goroslib.NewSubscriber(goroslib.SubscriberConf{
		Node:  commonConfig.RosNode,
		Topic: config.TopicOfFaultInfo,
		Callback: func(data *pjisuv_msgs.FaultVec) {
			codeString := ""
			for _, info := range data.InfoVec {
				codeString = codeString + util.ToString(info.ErrorCode)
			}
			faultLogger.Errorf("接收到故障码：【%v】", codeString)
		},
	})
}

func uploadLodRegularly() {
	// 1 创建一个定时器，每隔一秒触发一次
	ticker := time.NewTicker(regularTime)
	// 2 使用goroutine运行一个无限循环
	go func() {
		for {
			select {
			// 定时器触发时执行的代码
			case <-ticker.C:
				commonConfig.OssMutex.Lock()
				err := commonConfig.OssBucket.PutObjectFromFile(commonConfig.OssEquBasePrefix+"fault_code/"+filepath.Base(logPath), logPath)
				commonConfig.OssMutex.Unlock()
				if err != nil {
					c_log.GlobalLogger.Error("上传故障码日志失败：", err)
				}
			}
		}
	}()
}
