package dao

import (
	"time"
)

//CheckPoint 卡口
type CheckPoint struct {
	ID            int       `gorm:"primary_key" json:"id"`                  //编号
	PointName     string    `gorm:"type:varchar(64)" json:"pointName"`      //卡口名称
	PointSN       string    `gorm:"type:varchar(60)" json:"pointSn"`        //卡口编码
	PointLocation string    `gorm:"type:varchar(150)" json:"pointLocation"` //卡口位置
	TenantId      string    `gorm:"type:varchar(12)" json:"tenantId"`       //租户ID
	CreateTime    time.Time `gorm:"type:datetime" json:"createTime"`        //新增时间
	CreateUser    int64     `gorm:"type:bigint" json:"createUser"`          //新增记录操作用户ID
	UpdateTime    time.Time `gorm:"type:datetime" json:"updateTime"`        //修改时间
	UpdateUser    int64     `gorm:"type:bigint" json:"updateUser"`          //修改用户
	IsDeleted     int       `gorm:"type:int;default 0" json:"isDeleted"`    //是否删除 0=未删除,1=删除
}

func (CheckPoint) TableName() string {
	return "device_check_point"
}

func (c CheckPoint) IsExistedBySN() bool {
	var count int64
	_ = Db.Debug().Model(&c).Where("point_sn = ? and is_deleted = ?",
		c.PointSN, c.IsDeleted).Count(&count).Error
	return count > 0
}

func (c *CheckPoint) Create() error {
	return Db.Debug().Model(&c).Save(&c).Error
}

func (c *CheckPoint) Update() error {
	return Db.Debug().Model(&c).Where(" id = ? ", c.ID).Updates(&c).Error
}

func (c *CheckPoint) GetDevice() error {
	err := Db.Debug().Model(&c).Where(" id = ? ", c.ID).First(&c).Error
	return err
}

func (c CheckPoint) GetDevices(offset, limit int) ([]CheckPoint, int64, error) {
	var Points []CheckPoint
	var count int64
	db := Db.Debug().Model(&c)
	if c.PointSN != "" {
		db = db.Where("point_name like ? or point_sn like ?", "%"+c.PointSN+"%", "%"+c.PointSN+"%")
	}
	db = db.Where("is_deleted = 0")
	db.Count(&count)
	err := db.Offset(offset).Limit(limit).Find(&Points).Error
	return Points, count, err
}

func (c *CheckPoint) Delete() error {
	return Db.Debug().Model(&c).Where("id = ?", c.ID).Updates(map[string]interface{}{"update_time": c.UpdateTime,
		"update_user": c.UpdateUser, "is_deleted": c.IsDeleted}).Error
}

func (c CheckPoint) GetAllDevices() ([]*CheckPoint, error) {
	var Points []*CheckPoint
	err := Db.Debug().Model(&c).Where(" tenant_id = ? and is_deleted = ? ", c.TenantId, c.IsDeleted).Scan(&Points).Error
	return Points, err
}
