package dao

import (
	"gorm.io/gorm"
	"iot_manager_service/util/common"
	"time"
)

// InfoBoard InfoBoard信息基本屏
type InfoBoard struct {
	ID               int         `gorm:"primary_key" json:"id"`                            //编号
	InfoName         string      `gorm:"type:varchar(60)" json:"infoName"`                 //名称
	Sn               string      `gorm:"type:varchar(60)" json:"sn"`                       //设备序列号
	LampPoleId       int         `gorm:"type:int" json:"lampPoleId"`                       //所属灯杆id
	LampPoleName     string      `gorm:"type:varchar(64)" json:"lampPoleName"`             //灯杆名称
	LampPoleSn       string      `gorm:"type:varchar(64)" json:"lampPoleSn"`               //灯杆编码
	LampPoleLocation string      `gorm:"type:varchar(255)" json:"lampPoleLocation"`        //灯杆安装位置
	PoleLng          float64     `gorm:"type:double(17, 14) " json:"lampLng"`              //经度
	PoleLat          float64     `gorm:"type:double(17, 14)  " json:"lampLat"`             //纬度
	GatewayId        int         `gorm:"type:int" json:"gatewayId"`                        //所属网关id
	GroupId          int         `gorm:"type:int" json:"groupId"`                          //所属灯杆分组
	Resolution       int         `gorm:"type:int" json:"resolution"`                       //分辨率
	BrandId          int         `gorm:"type:int" json:"brandId"`                          //设备名
	ModelId          int         `gorm:"type:int" json:"modelId"`                          //设备型号
	InfoSize         int         `gorm:"type:int" json:"infoSize"`                         //信息屏尺寸
	RatedPower       float32     `gorm:"type:float(8, 2); default 0.00" json:"ratedPower"` //额定功率(LED灯)
	IPAddress        string      `gorm:"type:varchar(64)" json:"ipAddress"`                //IP地址
	BootStartTime    string      `gorm:"type:varchar(64)" json:"bootStartTime"`            //开机开始时间
	BootEndTime      string      `gorm:"type:varchar(64)" json:"bootEndTime"`              //开机结束时间
	NeverCloseDown   int         `gorm:"type:int" json:"neverCloseDown"`                   //永不关机:1-选择,2-取消
	InstallTime      common.Time `gorm:"type:date" json:"installTime"`                     //安装时间
	TenantId         string      `gorm:"type:varchar(12)" json:"tenantId"`                 //租户ID
	CreateTime       time.Time   `gorm:"type:datetime" json:"createTime"`                  //新增时间
	CreateUser       int         `gorm:"type:int" json:"createUser"`                       //新增记录操作用户ID
	UpdateTime       time.Time   `gorm:"type:datetime" json:"updateTime"`                  //修改时间
	UpdateUser       int         `gorm:"type:int" json:"updateUser"`                       //修改用户
	IsDeleted        int         `gorm:"type:int;default 0" json:"isDeleted"`              //是否删除 0=未删除,1=删除
	Tag              string      `gorm:"type:varchar(255)" json:"tag"`                     //标签,保留字段(逗号区分)
	ExteriorUid      int         `gorm:"type:bigint" json:"exteriorUid"`                   //外设ID
	IsEnable         int         `gorm:"type:int; default 2 " json:"isEnable"`             //启用禁用:1启用,2禁用

	Condition string `gorm:"type:varchar(255);default='80,30,30,5'" json:"condition"` //白天晚上 亮度 音量调节
}

func (InfoBoard) TableName() string {
	return "device_info_board"
}

func (c InfoBoard) Delete() error {
	return Db.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 InfoBoard) IsExistedBySN() bool {
	var count int64
	_ = Db.Model(&c).Where("  sn = ? and is_deleted = ?",
		c.Sn, c.IsDeleted).Count(&count).Error
	return count > 0
}

func (c InfoBoard) IsExistedByNameAndCode() bool {
	var devices []InfoBoard
	err := Db.Model(&c).Where(" sn = ? and is_deleted = ?",
		c.Sn, c.IsDeleted).Find(&devices).Error
	//如果查询不到,返回相应的错误
	if gorm.ErrRecordNotFound == err {
		return false
	}
	for _, d := range devices {
		if d.ID != c.ID {
			return true
		}
	}
	return false
}

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

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

func (c *InfoBoard) GetDevice() (InfoBoard, error) {
	var device InfoBoard
	err := Db.Model(&c).Where(" is_deleted = 0 and id = ? ", c.ID).Scan(&device).Error
	return device, err
}

func (c InfoBoard) GetDevices(offset, limit int) ([]InfoBoard, int64, error) {
	var devices []InfoBoard
	var count int64
	db := Db.Model(&c).Where("is_deleted = 0  and (info_name like ? or sn like ?) ", "%"+c.InfoName+"%", "%"+c.InfoName+"%")
	db.Count(&count)
	err := db.Offset(offset).Limit(limit).Order("info_name asc").Find(&devices).Error
	return devices, count, err
}

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

func (c InfoBoard) GetAllDevicesNotTenant() ([]*InfoBoard, error) {
	var devices []*InfoBoard
	db := Db.Model(&c)
	if c.ID > 0 {
		db.Where("id=?", c.ID)
	}
	err := db.Where("is_deleted = 0 ").Scan(&devices).Error
	return devices, err
}

func (c InfoBoard) GetDevicesByGateway() []InfoBoard {
	var devices []InfoBoard
	Db.Model(&c).Where(" gateway_id = ? and is_deleted = 0",
		c.GatewayId).Find(&devices)
	return devices
}

func (c InfoBoard) GetDevicesByLampPole() []InfoBoard {
	var devices []InfoBoard
	Db.Model(&c).Where("lamp_pole_id = ? and is_deleted = 0",
		c.LampPoleId).Find(&devices)
	return devices
}

func (c InfoBoard) GetDevicesByResolution() []InfoBoard {
	var devices []InfoBoard
	Db.Model(&c).Where("resolution = ? and tenant_id = ? and is_deleted = 0",
		c.Resolution, c.TenantId).Find(&devices)
	return devices
}

func (c InfoBoard) GetDevicesByIds(ids string) []InfoBoard {
	var devices []InfoBoard
	Db.Model(&c).Where("id in ("+ids+")"+" and tenant_id = ?  and is_deleted = 0",
		c.TenantId).Scan(&devices)
	return devices
}

func (c InfoBoard) DeviceCount1() (int64, int64) {
	var all, fault int64
	err := Db.Model(&c).Where("is_deleted = 0").Count(&all).Error
	if err != nil {
		all = 0
	}
	err = Db.Model(&c).Where("is_deleted = 0 and status = 0").Count(&fault).Error
	if err != nil {
		fault = 0
	}
	return all, fault
}

func (c InfoBoard) ListDevices1() []Device {
	var devices []InfoBoard
	Db.Model(&c).Where("is_deleted = 0").Find(&devices)
	var rsp = make([]Device, 0, len(devices))
	for _, v := range devices {
		var d = Device{
			Lng:          v.PoleLng,
			Lat:          v.PoleLat,
			Status:       -1,
			Name:         v.InfoName,
			Code:         v.Sn,
			LampPoleName: v.LampPoleName,
			Model:        "模型",
		}
		rsp = append(rsp, d)
	}
	return rsp
}