common.go 2.8 KB
package utils

import (
	"fmt"
	timeconv "github.com/Andrew-M-C/go.timeconv"
	"github.com/beego/beego/v2/core/validation"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
	"reflect"
	"strings"
	"time"
)

// ValidateCommand 验证输入参数
func ValidateCommand(commandType interface{}) error {
	valid := validation.Validation{}
	b, err := valid.Valid(commandType)
	if err != nil {
		return err
	}
	if !b {
		elem := reflect.TypeOf(commandType).Elem()
		for _, validErr := range valid.Errors {
			field, isExist := elem.FieldByName(validErr.Field)
			if isExist {
				if tag := field.Tag.Get("cname"); len(tag) > 0 {
					return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, tag, -1))
				} else {
					return fmt.Errorf(validErr.Message)
				}
			} else {
				return fmt.Errorf(validErr.Message)
			}
		}
	}
	return nil
}

// NextTime 0点时刻为标准计算
func NextTime(now0 time.Time, start *time.Time, kpiCycle int) time.Time {
	// 起始时间0点时刻
	start0 := time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, time.Local)

	var nextTime time.Time
	switch kpiCycle {
	case domain.KpiCycleDay:
		nextTime = timeconv.AddDate(now0, 0, 0, 1) // 当前时间的下一天开始发送
		break
	case domain.KpiCycleWeek:
		offsetSeconds := int64(now0.Sub(start0).Seconds())
		offsetDay := offsetSeconds / (24 * 60 * 60)
		cycleCount := int(offsetDay)/7 + 1
		nextTime = timeconv.AddDate(start0, 0, 0, cycleCount*7)
		break
	case domain.KpiCycleOneMonth:
		nextTime = timeconv.AddDate(start0, 0, 1, 0)
		break
	case domain.KpiCycleTwoMonth:
		nextTime = timeconv.AddDate(start0, 0, 2, 0)
		break
	case domain.KpiCycleThreeMonth:
		nextTime = timeconv.AddDate(start0, 0, 3, 0)
		break
	case domain.KpiCycleSixMonth:
		nextTime = timeconv.AddDate(start0, 0, 6, 0)
		break
	case domain.KpiCycleYear:
		nextTime = timeconv.AddDate(start0, 1, 0, 0)
		break
	}
	return nextTime
}

// NextTimeInc 0点时刻为标准计算
func NextTimeInc(start *time.Time, kpiCycle int) time.Time {
	// 起始时间0点时刻
	start0 := time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, time.Local)

	var nextTime time.Time
	switch kpiCycle {
	case domain.KpiCycleDay:
		nextTime = timeconv.AddDate(start0, 0, 0, 1) // 当前时间的下一天开始发送
		break
	case domain.KpiCycleWeek:
		nextTime = timeconv.AddDate(start0, 0, 0, 7)
		break
	case domain.KpiCycleOneMonth:
		nextTime = timeconv.AddDate(start0, 0, 1, 0)
		break
	case domain.KpiCycleTwoMonth:
		nextTime = timeconv.AddDate(start0, 0, 2, 0)
		break
	case domain.KpiCycleThreeMonth:
		nextTime = timeconv.AddDate(start0, 0, 3, 0)
		break
	case domain.KpiCycleSixMonth:
		nextTime = timeconv.AddDate(start0, 0, 6, 0)
		break
	case domain.KpiCycleYear:
		nextTime = timeconv.AddDate(start0, 1, 0, 0)
		break
	}
	return nextTime
}