list_device_collection.go 2.0 KB
package query

import (
	"fmt"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
	"reflect"
	"strings"
	"time"

	"github.com/beego/beego/v2/core/validation"
)

type ListDeviceCollectionQuery struct {
	// 查询偏离量
	PageNumber int64 `cname:"查询偏离量" json:"pageNumber" `
	// 查询限制
	PageSize int64 `cname:"查询限制" json:"pageSize" valid:"Required"`
	// 设备类型
	DeviceType string `json:"deviceType" cname:"设备类型"`
	// 车间名
	WorkShopName string `json:"workShopName"`

	// 开始时间
	BeginTime string `cname:"开始时间" json:"beginTime"`
	// 结束时间
	EndTime string `cname:"结束时间" json:"endTime"`

	// 开始时间
	ProductBeginTime time.Time `cname:"开始时间" json:"productBeginTime"`
	// 结束时间
	ProductEndTime time.Time `cname:"结束时间" json:"productEndTime"`
}

func (cmd *ListDeviceCollectionQuery) Valid(validation *validation.Validation) {
	var err error
	if len(cmd.BeginTime) > 0 {
		if cmd.ProductBeginTime, err = time.ParseInLocation("2006-01-02 15:04:05", cmd.BeginTime, time.Local); err != nil {
			log.Logger.Error(err.Error())
			validation.Error("开始时间有误")
			return
		}
	}
	if len(cmd.EndTime) > 0 {
		if cmd.ProductEndTime, err = time.ParseInLocation("2006-01-02 15:04:05", cmd.EndTime, time.Local); err != nil {
			log.Logger.Error(err.Error())
			validation.Error("结束时间有误")
			return
		}
		if cmd.ProductBeginTime.Equal(cmd.ProductEndTime) {
			cmd.ProductEndTime = cmd.ProductEndTime.Add(time.Hour * 24)
		}
	}
}

func (cmd *ListDeviceCollectionQuery) ValidateQuery() error {
	valid := validation.Validation{}
	b, err := valid.Valid(cmd)
	if err != nil {
		return err
	}
	if !b {
		elem := reflect.TypeOf(cmd).Elem()
		for _, validErr := range valid.Errors {
			field, isExist := elem.FieldByName(validErr.Field)
			if isExist {
				return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
			} else {
				return fmt.Errorf(validErr.Message)
			}
		}
	}
	return nil
}