package devices

import (
	"gorm.io/gorm"
	"server/global"
	"time"
)

type Intersect struct {
	ID            int            `gorm:"primary_key" json:"id"`                 //编号
	IntersectName string         `gorm:"type:varchar(64)" json:"intersectName"` //路口名称
	IntersectType string         `gorm:"type:varchar(64)" json:"intersectType"` //路口类型
	Address       string         `gorm:"type:varchar(64)"  json:"address"`      //地址
	CreateTime    time.Time      `gorm:"type:datetime" json:"createTime"`       //创建时间
	IsDeleted     gorm.DeletedAt `gorm:"default:null" json:"isDeleted"`         //是否删除
	Status        int            `gorm:"type:int" json:"status"`                //运行状态 0=正常,1=异常
}

func (Intersect) TableName() string {
	return "dev_intersect"
}

func (i Intersect) PublicIntersect() (intersectList []Intersect, err error) {
	err = global.GVA_DB.Model(&Intersect{}).Select("id", "intersect_name", "address").Find(&intersectList).Error
	return
}

func (i Intersect) IsExistedByName() error {
	err := global.GVA_DB.Model(&Intersect{}).Where("intersect_name = ?", i.IntersectName).First(&i).Error
	return err
}

func (i Intersect) AddIntersect() error {
	err := global.GVA_DB.Model(&Intersect{}).Create(&i).Error
	return err
}

func (i Intersect) UpdateIntersect() error {
	err := global.GVA_DB.Model(&i).
		Select("intersect_name", "address", "intersect_type").
		Where("id=?", i.ID).
		Updates(map[string]interface{}{
			"intersect_name": i.IntersectName,
			"address":        i.Address,
			"intersect_type": i.IntersectType,
		}).Error
	return err
}

func (i Intersect) DelIntersect(id int) error {
	err := global.GVA_DB.Model(&i).Where("id = ?", id).Delete(&i).Error
	return err
}

func UpdateIntersectStatus(id string, status int) error {
	var intersect Intersect
	err := global.GVA_DB.Model(&intersect).
		Select("status").
		Where("id = ?", id).
		Updates(map[string]interface{}{
			"status": status,
		}).Error
	return err
}

func QueryIntersectInfoList(limit, offset int, keyword, shunt string) (intersectList []Intersect, total int64, err error) {
	db := global.GVA_DB.Model(&Intersect{})
	if keyword != "" {
		db.Where("intersect_name like ? ", "%"+keyword+"%")
	}
	if shunt != "" {
		db.Where("intersect_type like ?", "%"+shunt+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Find(&intersectList).Error
	return
}
