package schedule

import (
	common "LAPP_ACURA_MOM_BACKEND/models/base"
	"log"
	"reflect"
	"strings"
	"time"
)

// 基于时间单位获取秒数
func GetTimeUomSeconds(uomId string) (seconds float64) {
	seconds = 0
	switch strings.ToUpper(uomId) {
	case common.TIME_UOM_WEEK:
		seconds = 7 * 24 * 3600
	case common.TIME_UOM_DAY:
		seconds = 24 * 3600
	case common.TIME_UOM_HOUR:
		seconds = 3600
	case common.TIME_UOM_MINUTE:
		seconds = 60
	case common.TIME_UOM_SECOND:
		seconds = 1
	}

	return
}

// 设置表的更新时间
func SetTableLastModify(sp interface{}, s interface{}, setMode string, lastUser string) {
	var (
		hasLastmodify, hasLastuser, hasCreatetime bool
	)

	avp := reflect.ValueOf(sp)
	av := reflect.ValueOf(s)
	at := reflect.TypeOf(s)
	// 简单判断下是否为结构体
	if at.Kind() != reflect.Struct {
		log.Printf("s must be a struct")
		return
	}
	// 判断是否有LastModify
	hasLastmodify = false
	hasLastuser = false
	hasCreatetime = false
	avp = reflect.ValueOf(avp.Interface())

	for i := 0; i < av.NumField(); i++ {
		if at.Field(i).Name == "Lastmodify" {
			hasLastmodify = true
		}
		if at.Field(i).Name == "Lastuser" {
			hasLastuser = true
		}
		if at.Field(i).Name == "Createtime" {
			hasCreatetime = true
		}
	}
	if hasLastmodify && hasLastuser && hasCreatetime {
		switch setMode {
		case common.MODIFY_MODE_CREATE:
			f1 := avp.Elem().FieldByName("Createtime")
			f1.Set(reflect.ValueOf(time.Now()))
			f2 := avp.Elem().FieldByName("Lastuser")
			if lastUser != "" {
				f2.Set(reflect.ValueOf(lastUser))
			} else {
				f2.Set(reflect.ValueOf("sys_service"))
			}

		case common.MODIFY_MODE_UPDATE:
			f1 := avp.Elem().FieldByName("Lastmodify")
			f1.Set(reflect.ValueOf(time.Now()))
			f2 := avp.Elem().FieldByName("Lastuser")
			if lastUser != "" {
				f2.Set(reflect.ValueOf(lastUser))
			} else {
				f2.Set(reflect.ValueOf("sys_service"))
			}

		case common.MODIFY_MODE_DELETE:
		}
	}
}
