package dao

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

// ManholeCover 井盖基本信息
type ManholeCover struct {
	ID                  int        `gorm:"primary_key" json:"id"`                    //编号
	ManholeName         string     `gorm:"type:varchar(64)" json:"manholeName"`      //设备名称
	ManholeSn           string     `gorm:"type:varchar(60)" json:"manholeSn"`        //设备序列号
	DeviceIMei          string     `gorm:"type:varchar(64)" json:"deviceIMei"`       //IMEI-唯一不允许重复
	BrandId             int        `gorm:"type:int" json:"brandId"`                  //设备名称
	ModelId             int        `gorm:"type:int" json:"modelId"`                  //设备型号
	KindType            int        `gorm:"type:int" json:"kindType"`                 //种类
	Radius              int        `gorm:"type:int" json:"radius"`                   //半径
	MaterialQuality     int        `gorm:"type:int" json:"materialQuality"`          //材质
	InstallLocationType int        `gorm:"type:int" json:"installLocationType"`      //安装位置类型
	WayName             string     `gorm:"type:varchar(60)" json:"wayName"`          //所属道路
	InstallTime         *time.Time `gorm:"type:date" json:"installTime"`             //安装时间
	ProvinceName        string     `gorm:"varchar(12)" json:"provinceName"`          //省份
	CityName            string     `gorm:"type:varchar(12)" json:"cityName"`         //市
	DistrictName        string     `gorm:"type:varchar(12)" json:"districtName"`     //区
	InstallLocation     string     `gorm:"type:varchar(100)" json:"installLocation"` //安装位置
	Latitude            float64    `gorm:"type:double(17, 14) " json:"latitude"`     //纬度
	Longitude           float64    `gorm:"type:double(17, 14)  " json:"longitude"`   //经度
	PhotoUrl            string     `gorm:"type:varchar(255) " json:"photoUrl"`       //照片地址
	Remark              string     `gorm:"type:varchar(1000)  " json:"remark"`       //备注
	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"`             //标签，保留字段(逗号区分)
	Threshold           string     `gorm:"type: varchar(255)" json:"threshold"`      //阈值
	CameraId            int        `gorm:"type:int" json:"cameraId"`                 //归属摄像机id
	CameraSn            string     `gorm:"type: varchar(60) " json:"cameraSn"`       //归属摄像机sn

	LeanAngleAlarm int     `json:"leanAngleAlarm"`                         //告警倾斜
	BatteryAlarm   float64 `gorm:"type: varchar(60) " json:"batteryAlarm"` //告警电压
	MinTemp        float64 `gorm:"type: varchar(60) " json:"minTemp"`      //低温阈值
	MaxTemp        float64 `gorm:"type: varchar(60) " json:"maxTemp"`      //高温阈值

	LeanAngle    int         `json:"leanAngle"`                         //倾斜角度
	Temperature  float64     `json:"temperature"`                       //温度
	BatteryLevel float64     `json:"batteryLevel"`                      //电压
	Csq          int         `json:"csq"`                               //信号
	LastPostTime common.Time `gorm:"type:datetime" json:"lastPostTime"` //最后上报时间
}

func (ManholeCover) TableName() string {
	return "device_manhole_cover"
}

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

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

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

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

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

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

func (c ManholeCover) FindDeviceIdByImei(imei string) (int, error) {
	var device ManholeCover
	err := Db.Debug().Raw("SELECT * FROM `device_manhole_cover` WHERE `device_i_mei` = ? AND `is_deleted` = '0' limit 1", imei).First(&device).Error
	return device.ID, err
}
