package dao

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

type Screens struct {
	ID          uint           `gorm:"primarykey" json:"ID"`                //主键ID
	ScreensName string         `gorm:"type:varchar(64)" json:"screensName"` //设备名称
	Sn          string         `gorm:"type:varchar(64)" json:"sn"`          //设备sn
	ProjectId   uint           `gorm:"type:int" json:"projectId"`           //所属项目
	IPAddress   string         `gorm:"type:varchar(40)" json:"ipAddress"`   //IP地址
	Remark      string         `gorm:"type:varchar(60)" json:"Remark"`      //备注
	IsDeleted   gorm.DeletedAt `gorm:"default:null" json:"isDeleted"`       //是否删除
	Status      int            `gorm:"type:int;default:0" json:"status"`    //在线状态 0=离线,1=在线

	Project Project `gorm:"foreignkey:ProjectId"`

	ProgramId int     `gorm:"type:int" json:"programId"` // 节目id
	Program   Program `gorm:"foreignkey:ProgramId"`

	SoundPeriodId int         `gorm:"type:int" json:"soundPeriodId"`
	SoundPeriod   SoundPeriod `gorm:"foreignkey:SoundPeriodId"`
}

func (Screens) TableName() string {
	return "dev_screens"
}

func (s Screens) AddScreens() error {
	return global.GVA_DB.Model(&Screens{}).Create(&s).Error
}

func (s Screens) DelScreens(id int) error {
	err := global.GVA_DB.Model(&s).Where("id = ?", id).Delete(&s).Error
	return err
}

func (s Screens) GetScreensList(limit, offset, projectId int, sn string, uid uint) (screensList []Screens, total int64, err error) {

	db := global.GVA_DB.Model(&Screens{})

	if sn != "" {
		db.Where("sn like ?", "%"+sn+"%")
	}

	if projectId != 0 {
		db.Where("project_id = ?", projectId)
	} else {
		var projectIds []uint
		list, _ := GetProjectListByUserIDNoPage(uid)
		for _, project := range list {
			projectIds = append(projectIds, project.ID)
		}
		db.Where("project_id in (?)", projectIds).Order("id DESC ")
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Preload("SoundPeriod").Preload("Program").Preload("Project").Find(&screensList).Error
	return
}

func (s Screens) UpdateScreens() error {
	return global.GVA_DB.Model(&Screens{}).Where("id = ?", s.ID).Updates(map[string]interface{}{
		"screens_name": s.ScreensName,
		"sn":           s.Sn,
		"project_id":   s.ProjectId,
		"ip_address":   s.IPAddress,
		"remark":       s.Remark,
	}).Error
}

func QueryScreensToDetail(id uint) (screensList []Screens, err error) {
	db := global.GVA_DB.Model(&Screens{})
	err = db.Where("project_id = ?", id).Find(&screensList).Error
	return
}

func QueryAllScreens() (screensList []Screens, err error) {
	err = global.GVA_DB.Model(&Screens{}).Find(&screensList).Error
	return
}

func QueryScreensBySn(sn string) (screen Screens, err error) {
	err = global.GVA_DB.Model(&Screens{}).Where("sn = ?", sn).Find(&screen).Error
	return
}

func UpdateScreensStatusBySn(sn string, status int) (err error) {
	err = global.GVA_DB.Model(&Screens{}).Where("sn = ?", sn).Update("status", status).Error
	return
}
