package dao

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

//OptoSensor 集控器
type OptoSensor struct {
	ID               int         `gorm:"primary_key" json:"id"`                     //编号
	Name             string      `gorm:"type:varchar(64)" json:"name"`              //名称
	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"` //灯杆安装位置
	LampLng          float64     `gorm:"type:double(17, 14) " json:"lampLng"`       //经度
	LampLat          float64     `gorm:"type:double(17, 14)  " json:"lampLat"`      //纬度
	BrandId          int         `gorm:"type:int" json:"brandId"`                   //设备名称
	ModelId          int         `gorm:"type:int" json:"modelId"`                   //设备型号
	GatewayId        int         `gorm:"type:int" json:"gatewayId"`                 //所属网关id
	InstallTime      common.Time `gorm:"type:date" json:"installTime"`              //安装时间
	IPAddress        string      `gorm:"type:varchar(64)" json:"ipAddress"`         //IP地址-备用
	IsDefault        int         `gorm:"type:int;default 0" json:"isDefault"`       //是否设为首页默认展示 0=不展示,1=设置展示
	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=删除
	Status           int         `gorm:"type:int" json:"status"`                    //状态 0=正常,1=异常
	Tag              string      `gorm:"type:varchar(255)" json:"tag"`              //标签，保留字段(逗号区分)
}

func (OptoSensor) TableName() string {
	return "device_opto_sensor"
}

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

func (c OptoSensor) IsExistedByNameAndCode() bool {
	var devices []Zigbee
	err := Db.Debug().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 *OptoSensor) Create() error {
	return Db.Debug().Model(&c).Save(&c).Error
}

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

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

func (c OptoSensor) GetDevices(offset, limit int) ([]OptoSensor, int64, error) {
	var devices []OptoSensor
	var count int64
	db := Db.Debug().Model(&c).Where("is_deleted=0 and name like ? ", "%"+c.Name+"%")
	db.Count(&count)
	err := db.Offset(offset).Limit(limit).Find(&devices).Error
	return devices, count, err
}

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

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

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

func (c OptoSensor) GetDevicesByTenantId() []OptoSensor {
	var devices []OptoSensor
	Db.Debug().Model(&c).Where("tenant_id = ? and is_deleted = 0",
		c.TenantId).Find(&devices)
	return devices
}

func (c OptoSensor) GetAll() []*OptoSensor {
	var devices []*OptoSensor
	Db.Debug().Model(&c).Where("is_deleted = 0").Find(&devices)
	return devices
}

func (c OptoSensor) getList(optoSensor OptoSensor) []OptoSensorVO {
	var optoSensorVO []OptoSensorVO
	tenantId := optoSensor.TenantId
	if tenantId == "" {
		tenantId = c.TenantId
	}
	optoSensor.TenantId = tenantId
	where := ""
	if optoSensor.IsDefault == 1 {
		where = "and a.is_default=1"
	}
	Db.Model(&c).Debug().Raw("SELECT a.*, v3.id brand, v4.id model, lamp.district_name FROM device_opto_sensor a LEFT JOIN device_vendor v3 ON v3.id = a.brand_id LEFT JOIN device_vendor v4 ON v4.id = a.model_id LEFT JOIN device_lamp_pole lamp ON lamp.id = a.lamp_pole_id WHERE a.is_deleted = 0 " + where).Scan(&optoSensorVO)

	return optoSensorVO
}
