package dao

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

// SwitchBox 供电箱
type SwitchBox struct {
	ID             int         `gorm:"primary_key" json:"id"`                             //编号
	BoxName        string      `gorm:"type:varchar(64)" json:"boxName"`                   //供电箱名称
	BoxSN          string      `gorm:"type:varchar(60)" json:"boxSn"`                     //设备序列号
	BrandId        int         `gorm:"type:int" json:"brandId"`                           //品牌
	ModelId        int         `gorm:"type:int" json:"modelId"`                           //配电箱型号
	TransformerId  int         `gorm:"type:int" json:"transformerId"`                     //变压器ID
	TransformerNum string      `gorm:"type:varchar(60)" json:"transformerNum"`            //变压器出线口编号
	RatedPower     float32     `gorm:"type:double(8, 2) default 0.00 " json:"ratedPower"` //功率
	ProvinceName   string      `gorm:" type:varchar(12)" json:"provinceName"`             //省份
	CityName       string      `gorm:"type:varchar(12)" json:"cityName"`                  //市
	DistrictName   string      `gorm:"type:varchar(12)" json:"districtName"`              //区
	BoxLocation    string      `gorm:"type:varchar(100)" json:"boxLocation"`              //详细位置
	PoleLng        float64     `gorm:"type:double(17, 14) " json:"poleLng"`               //经度
	PoleLat        float64     `gorm:"type:double(17, 14)  " json:"poleLat"`              //纬度
	MonitorAddress string      `gorm:"type:varchar(255)   " json:"monitorAddress"`        //监控地址
	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     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"`                      //标签，保留字段(逗号区分)
	BoxPhotoUrl    string      `gorm:"type:varchar(255)" json:"boxPhotoUrl"`              //供电箱照片地址

	CountLampPole int64 `gorm:"-" json:"countLampPole" comment:"关联灯杆数" default:0`
}

func (SwitchBox) TableName() string {
	return "device_switch_box"
}

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

func (c SwitchBox) IsExistedByNameAndCode() bool {
	var devices []SwitchBox
	err := Db.Debug().Model(&c).Where(" box_sn = ? and is_deleted = ?",
		c.BoxSN, 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 *SwitchBox) Create() error {
	return Db.Debug().Model(&c).Save(&c).Error
}

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

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

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

//得到关联设备 2022-12-08 dsx
func (c SwitchBox) GetDeviceCount() (int64, error) {
	var count int64
	err := Db.Debug().Model(&c).Where("(transformer_id = ?) and is_deleted = 0",
		c.TransformerId).Count(&count).Error
	return count, err
}

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