diff --git a/service/peak_valley.go b/service/peak_valley.go index 557528b..311f447 100644 --- a/service/peak_valley.go +++ b/service/peak_valley.go @@ -115,11 +115,26 @@ func (r *PeakValley) CreatePeakValleyRule(req *form.CreatePeakValleyRuleReq) { var timeBlockIds []uint var timeBlockIdsMap = make(map[string][]uint) + var timeGroup [][]int for _, item := range req.RuleItem { start, end, blockTotal, err = utils.GetMinutesFromTimeRange(item.StartTime, item.EndTime) if err != nil { return } + + if start > end { + err = errors.New("开始时间大于结束时间") + return + } + + in := []int{start, end} + timeGroup = append(timeGroup, in) + if utils.HasOverlap(timeGroup) { + err = errors.New("选择的时间段与其他时间段有重叠") + return + } + + // 总时常判断 total += blockTotal if total > peak_valley_model.MinutesInADay { err = errors.New("选择的时间段超过一天") @@ -195,11 +210,25 @@ func (r *PeakValley) UpdatePeakValleyRule(req *form.UpdatePeakValleyRuleReq) { var timeBlockIds []uint var timeBlockIdsMap = make(map[string][]uint) + var timeGroup [][]int for _, item := range req.RuleItem { start, end, blockTotal, err = utils.GetMinutesFromTimeRange(item.StartTime, item.EndTime) if err != nil { return } + + if start > end { + err = errors.New("开始时间大于结束时间") + return + } + + in := []int{start, end} + timeGroup = append(timeGroup, in) + if utils.HasOverlap(timeGroup) { + err = errors.New("选择的时间段与其他时间段有重叠") + return + } + // 总时常判断 total += blockTotal if total > peak_valley_model.MinutesInADay { err = errors.New("选择的时间段超过一天") diff --git a/utils/utils.go b/utils/utils.go index cbc6cb5..91d5db5 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -187,3 +187,39 @@ func SplitIntoGroups(nums []int) [][]int { return groups } + +// IsInRange 检查一个整数是否在指定的区间内 +func IsInRange(number, lowerBound, upperBound int) bool { + return number >= lowerBound && number <= upperBound +} + +// Interval 表示一个区间 +type Interval struct { + start int + end int +} + +// ByStart 实现 sort.Interface 接口,用于按区间的开始位置排序 +type ByStart []Interval + +func (a ByStart) Len() int { return len(a) } +func (a ByStart) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a ByStart) Less(i, j int) bool { return a[i].start < a[j].start } + +// HasOverlap 检查切片中的所有区间是否有重叠 +func HasOverlap(timeGroup [][]int) bool { + // 将切片转换为 Interval 结构体切片 + var intervals []Interval + for _, interval := range timeGroup { + intervals = append(intervals, Interval{start: interval[0], end: interval[1]}) + } + // 按照区间的开始位置排序 + sort.Sort(ByStart(intervals)) + // 检查相邻区间是否重叠 + for i := 0; i < len(intervals)-1; i++ { + if intervals[i].end > intervals[i+1].start { + return true + } + } + return false +}