package dao

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

type Device struct {
	global.GVA_MODEL
	Sn                string              `json:"sn" gorm:"comment:设备sn"`
	Name              string              `json:"name" gorm:"comment:名称"`
	State             bool                `json:"state" gorm:"comment:设备状态"`
	Address           string              `json:"address" gorm:"comment:设备地址"`
	TaskTime          uint                `json:"taskTime" gorm:"comment:采集时间"`
	WaitTime          uint                `json:"waitTime" gorm:"comment:延迟时间"`
	RadarId           int8                `json:"radarId" gorm:"comment:雷达id"`
	SerialId          int8                `json:"serialId" gorm:"comment:串口id"`
	Genre             int                 `json:"genre" gorm:"index;comment:类型id"`
	DeviceGenre       DeviceGenre         `json:"deviceGenre" gorm:"foreignKey:Genre;"`
	TunnelId          int                 `json:"tunnelId" gorm:"column:tunnel_id"`
	Tunnel            Tunnel              `json:"tunnel" gorm:"foreignKey:TunnelId"`
	DeviceRelays      []DeviceRelay       `json:"deviceRelays" gorm:"foreignKey:DeviceSn;references:Sn"`
	InductanceDetails []InductanceDetails `json:"inductanceDetails" gorm:"foreignKey:DeviceSn;references:Sn"`
}

func (Device) TableName() string {
	return "device"
}

func QueryAllDevices() (devices []Device, err error) {
	err = global.GVA_DB.Model(Device{}).Preload("DeviceGenre").Preload("DeviceRelays").Preload("Tunnel").Find(&devices).Error
	return
}

func QueryDeviceList(sn, name string, genre, limit, offset int) (devices []Device, total int64, err error) {
	db := global.GVA_DB.Model(Device{})

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

	if name != "" {
		db = db.Where("name LIKE ?", "%"+name+"%")
	}

	if genre != 0 {
		db = db.Where("genre = ?", genre)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Preload("DeviceGenre").Preload("DeviceRelays").Preload("Tunnel").Find(&devices).Error
	return
}

func QueryDeviceByTunnelId(id int) (devices []Device, err error) {
	err = global.GVA_DB.Where("tunnel_id =?", id).Preload("DeviceGenre").Preload("DeviceRelays").Preload("Tunnel").Find(&devices).Error
	return
}

func QueryGenreByTunnel(id int) (devices []Device, err error) {
	err = global.GVA_DB.Model(&Device{}).
		Select("device.*").
		Joins("JOIN device_genre ON device.genre = device_genre.id").
		Where("device.tunnel_id = ? AND device_genre.type = ?", id, "开关设备").
		Find(&devices).Error
	return
}

func QueryDeviceByTunnelSnAndRadarId(sn string, id int) (device Device, err error) {
	err = global.GVA_DB.Model(&Device{}).
		Select("device.*").
		Joins("JOIN tunnel ON device.tunnel_id = tunnel.id").
		Where("device.radar_id = ? AND tunnel.tunnel_sn = ?", id, sn).
		First(&device).Error
	return
}

func QueryDGDeviceByTunnelSn(tunnelSn string) (device Device, err error) {
	err = global.GVA_DB.Model(&Device{}).
		Where("genre = 7 AND tunnel_sn = ?", tunnelSn).
		First(&device).Error
	return
}

func (d Device) CreateDevice() error {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		err := tx.Create(&d).Error
		if err != nil {
			return err
		}
		if d.Genre == 6 {
			var deviceRelays []DeviceRelay
			for i := 1; i <= 4; i++ {
				relay := DeviceRelay{
					RelayID:  i,
					DeviceSn: d.Sn,
					State:    false,
				}
				deviceRelays = append(deviceRelays, relay)
			}
			return tx.Create(&deviceRelays).Error
		}
		return nil
	})
}

func (d Device) UpdateDevice() error {
	return global.GVA_DB.Debug().Where("id = ?", d.ID).Updates(&d).Error
}

func DeleteDevice(id int) error {
	return global.GVA_DB.Unscoped().Where("id = ?", id).Delete(&Device{}).Error
}
