package dao

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

//LampPole 灯杆设备
type LampPole struct {
	ID              int         `gorm:"primary_key" json:"id"`                    //编号
	PoleName        string      `gorm:"type:varchar(64)"  json:"poleName"`        //灯杆名称
	PoleSN          string      `gorm:"type:varchar(60)" json:"poleSn"`           //灯杆唯一识别码
	PoleSize        float32     `gorm:"type:double(3,1)" json:"poleSize"`         //灯杆规格
	GroupId         int         `gorm:"type:int" json:"groupId"`                  //所属灯杆分组
	GatewayId       string      `gorm:"type:varchar(32)" json:"gatewayId"`        //所属网关id
	BoxId           int         `gorm:"type:int" json:"boxId"`                    //所属配电箱
	CoordType       int         `gorm:"type:int;default 1" json:"coordType"`      //经纬度类型0=百度,1=高德,2=腾讯,3=GPS
	ProvinceName    string      `gorm:"type:varchar(60)" json:"provinceName"`     //省份
	CityName        string      `gorm:"type:varchar(60)" json:"cityName"`         //城市
	DistrictName    string      `gorm:"type:varchar(60)" json:"districtName"`     //区域
	InstallLocation string      `gorm:"type:varchar(100)" json:"installLocation"` //安装位置
	PoleLng         float64     `gorm:"type:double(17,14)" json:"poleLng"`        //经度
	PoleLat         float64     `gorm:"type:double(17,14)" json:"poleLat"`        //纬度
	RealLng         float64     `gorm:"type:double(17,14)" json:"realLng"`        //真实经度
	RealLat         float64     `gorm:"type:double(17,14)" json:"realLat"`        //真实纬度
	IsCross         int         `gorm:"type:int" json:"isCross"`                  //是否为路口-0-是1-不是
	InstallTime     common.Time `gorm:"type:date" json:"installTime"`             //安装时间
	LampPolePhoto   string      `gorm:"type:varchar(255)" json:"lampPolePhoto"`   //灯杆照片
	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"`             //标签，(备用，逗号区分)
	BridgeId        int         `gorm:"type:int" json:"bridgeId"`                 //桥梁ID
}

func (LampPole) TableName() string {
	return "device_lamp_pole"
}

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

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

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

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

func (c LampPole) GetDevices(offset, limit int) ([]LampPole, int64, error) {
	var devices []LampPole
	var count int64
	db := Db.Debug().Model(&c)
	if c.PoleSN != "" {
		db = db.Where("pole_name like ? or pole_sn like ?", "%"+c.PoleSN+"%", "%"+c.PoleSN+"%")
	}
	if c.GroupId != -1 {
		db = db.Where("group_id = ?", c.GroupId)
	}
	if c.BoxId != -1 {
		db = db.Where("box_id = ?", c.BoxId)
	}
	db = db.Where("is_deleted = 0")
	db.Count(&count)
	err := db.Offset(offset).Limit(limit).Find(&devices).Error
	return devices, count, err
}

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

func (c LampPole) Count() int64 {
	var count int64
	_ = Db.Debug().Model(&c).Where(" group_id = ? and is_deleted = ?",
		c.GroupId, c.IsDeleted).Count(&count).Error
	return count
}

// GetSwitchBoxCount 得到 配电箱 关联灯杆数 2022-12-08 dsx
func (c LampPole) GetSwitchBoxCount() (int64, error) {
	var count int64
	err := Db.Debug().Model(&c).Where("(box_id = ?) and is_deleted = 0",
		c.BoxId).Count(&count).Error
	return count, err
}

// GetGroupIdCount 得到 灯杆分组 关联灯杆数 2022-12-09 dsx
func (c LampPole) GetGroupIdCount() (int, error) {
	var count int64
	err := Db.Debug().Model(&c).Where("(group_id = ?) and is_deleted = 0",
		c.GroupId).Count(&count).Error
	return int(count), err
}
