57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
package init_db_data
|
||
|
||
import (
|
||
"energy-management-system/global"
|
||
peak_valley_model "energy-management-system/model/peak-valley"
|
||
"github.com/gookit/color"
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
type InitPeakValleyTimeBlockData struct{}
|
||
|
||
var initPeakValleyTimeBlockData = new(InitPeakValleyTimeBlockData)
|
||
|
||
// type api struct{}
|
||
func buildData() (dataList []*peak_valley_model.PeakValleyTimeBlock) {
|
||
// 一天有24小时,即1440分钟
|
||
totalMinutes := 24 * 60
|
||
// 时间块的持续时间:10分钟
|
||
blockDuration := 10
|
||
// 遍历一天中的所有时间块
|
||
for i := 0; i < totalMinutes; i += blockDuration {
|
||
startTime := i
|
||
endTime := i + blockDuration
|
||
dataList = append(dataList, &peak_valley_model.PeakValleyTimeBlock{
|
||
StartTime: uint(startTime),
|
||
EndTime: uint(endTime),
|
||
})
|
||
}
|
||
return dataList
|
||
}
|
||
|
||
// Init 初始化用户数据
|
||
func (i *InitPeakValleyTimeBlockData) Init() error {
|
||
return global.Db.Transaction(func(tx *gorm.DB) error {
|
||
|
||
m := &peak_valley_model.PeakValleyTimeBlock{}
|
||
var count int64
|
||
|
||
err := tx.Model(&peak_valley_model.PeakValleyTimeBlock{}).Count(&count).Error
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
if count == 144 {
|
||
color.Danger.Println("\n[PGSQL] --> " + m.TableName() + " 表的初始数据已存在!")
|
||
return nil
|
||
}
|
||
|
||
dataList := buildData()
|
||
if err := tx.Create(&dataList).Error; err != nil { // 遇到错误时回滚事务
|
||
return err
|
||
}
|
||
color.Info.Println("\n[PGSQL] --> " + m.TableName() + "表初始数据成功!")
|
||
return nil
|
||
})
|
||
}
|