package internal

import (
	"goutil/fileUtil"
	"sync"
	"time"
)

var (
	sqlErrList     []string
	sqlErrListLock sync.RWMutex

	fileName = "ErrSql"
)

func init() {
	go func() {
		for {

			//休息一秒
			time.Sleep(time.Second)

			WriteErrSql()
		}
	}()
}

// AddSqlErr 添加异常sql
func AddSqlErr(sql string) {

	//数据库过大就不再写入
	if len(sqlErrList) > 10000 {
		return
	}

	func() {
		sqlErrListLock.Lock()
		defer sqlErrListLock.Unlock()
		sqlErrList = append(sqlErrList, sql)
	}()
}

// WriteErrSql 获取异常sql 写入文件
func WriteErrSql() {
	sqlErrListLock.RLock()
	defer sqlErrListLock.RUnlock()

	//文件名拼接
	filePath := fileName + "/" + time.Now().Format("2006-01-02")
	fileName := time.Now().Format("2006-01-02 09") + ".txt"

	for _, sql := range sqlErrList {
		//sql 添加换行符
		sql += ";\r\n"
		fileUtil.WriteFile(filePath, fileName, true, sql)

		//删除已经执行的sql
		sqlErrList = sqlErrList[1:]
	}
}
