Files
go-yu/utils/timeslot_generator.go

82 lines
2.4 KiB
Go
Raw Permalink Normal View History

2026-02-10 09:30:37 +08:00
package utils
import (
"fmt"
"time"
"yuyue/database"
"yuyue/models"
)
// GenerateTwoMonthsTimeSlots 生成最近两个月的预约时间槽
func GenerateTwoMonthsTimeSlots() error {
// 计算日期范围:明天开始的两个月
now := time.Now()
startDate := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location()) // 明天
endDate := startDate.AddDate(0, 2, 0) // 两个月后
fmt.Printf("开始生成时间槽:%s 到 %s\n", startDate.Format("2006-01-02"), endDate.Format("2006-01-02"))
generatedSlots := []models.TimeSlot{}
conflictCount := 0
currentDate := startDate
for !currentDate.After(endDate) {
// 排除周末
weekday := currentDate.Weekday()
if weekday == time.Saturday || weekday == time.Sunday {
currentDate = currentDate.AddDate(0, 0, 1)
continue
}
// 生成工作日的时间槽 (9:00-18:00每小时一个时段)
startTime := time.Date(currentDate.Year(), currentDate.Month(), currentDate.Day(),
9, 0, 0, 0, currentDate.Location())
endTime := time.Date(currentDate.Year(), currentDate.Month(), currentDate.Day(),
18, 0, 0, 0, currentDate.Location())
currentSlotTime := startTime
for currentSlotTime.Before(endTime) {
slotEnd := currentSlotTime.Add(time.Hour)
// 检查是否已经存在相同的时间槽
var existingSlot models.TimeSlot
err := database.GetDB().Where("date = ? AND start_time = ? AND end_time = ?",
currentDate, currentSlotTime, slotEnd).First(&existingSlot).Error
if err != nil {
// 不存在,创建新的时间槽
newSlot := models.TimeSlot{
Date: currentDate,
StartTime: currentSlotTime,
EndTime: slotEnd,
MaxPeople: 5, // 每个时段最多5人
CurrentPeople: 0,
IsActive: true,
}
generatedSlots = append(generatedSlots, newSlot)
} else {
conflictCount++
}
currentSlotTime = slotEnd
}
currentDate = currentDate.AddDate(0, 0, 1)
}
// 批量插入到数据库
if len(generatedSlots) > 0 {
if err := database.GetDB().CreateInBatches(generatedSlots, 100).Error; err != nil {
return fmt.Errorf("批量创建时间槽失败: %v", err)
}
fmt.Printf("成功生成 %d 个时间槽\n", len(generatedSlots))
}
if conflictCount > 0 {
fmt.Printf("跳过 %d 个已存在的时间槽\n", conflictCount)
}
fmt.Printf("总共处理 %d 个时间槽\n", len(generatedSlots)+conflictCount)
return nil
}