package dao

import (
	"errors"
	"gorm.io/gorm"
	"iot_manager_service/app/operation/model"
	"iot_manager_service/util/common"
)

type CaptureOverSpeed struct {
	ID        int         `gorm:"comment:ID" json:"id"`
	CaptureSn string      `gorm:"comment:抓拍单元SN" json:"code"`
	Time      common.Time `gorm:"comment:抓拍时间;type:datetime" json:"time"`
	Vtype     int         `gorm:"comment:车类型" json:"vtype"`
	Plate     string      `gorm:"comment:车牌号" json:"plate"`
	Speed     int         `gorm:"comment:速度" json:"speed"`
	Sflag     int         `gorm:"comment:速度比率" json:"sflag"`
}

func (c CaptureOverSpeed) TableName() string {
	return "data_capture_over_speed"
}

// GetMaxIdAndUpDateTime 得到最大同步 ID
func (c CaptureOverSpeed) GetMaxIdAndUpDateTime() (int64, string) {
	var captureOverSpeed CaptureOverSpeed
	err := Db.Debug().Model(&c).Last(&captureOverSpeed).Error
	if err != nil {
		return 0, ""
	}
	return int64(captureOverSpeed.ID), captureOverSpeed.Time.String()
}

// BatchCreate 批量插入
func (c CaptureOverSpeed) BatchCreate(his []CaptureOverSpeed) error {
	return Db.Debug().Model(&c).CreateInBatches(his, 1000).Error
}

// Gets 记录列表
func (c CaptureOverSpeed) Gets(captureSn string, req model.RequestCaptureOverSpeed) ([]CaptureOverSpeed, int64, error) {
	//fmt.Printf("size = %v \n", size)
	//fmt.Printf("current = %v \n", current)
	var list []CaptureOverSpeed
	db := Db.Debug().Model(&c).Where(&CaptureOverSpeed{CaptureSn: captureSn})
	db.Where("time between ? and ?", req.StartTime+" 00:00:00", req.EndTime+" 23:59:59")
	var count int64
	db.Count(&count)
	db = db.Scopes(common.Paginate(req.Current, req.Size))
	err := db.Order("id desc").Find(&list).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	//fmt.Printf("count = %v", count)
	return list, count, err
}
