package dao

import (
	"time"
)

// DeviceVendor 厂家
type DeviceVendor struct {
	ID          int       `gorm:"primary_key" json:"id"`                //编号
	VendorType  int       `gorm:"int" json:"vendorType"`                //类型：1-厂家名称，2-品牌，3-型号
	VendorValue string    `gorm:"type:varchar(200)" json:"vendorValue"` //值
	ParentId    int       `gorm:"type:int" json:"parentId"`             //父id，厂家为-1
	DeviceType  int       `gorm:"type:int" json:"deviceType"`           //设备类型
	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" json:"isDeleted"`            //是否删除 0=未删除,1=删除
}

func (DeviceVendor) TableName() string {
	return "device_vendor"
}

func (c *DeviceVendor) GetVendor() ([]DeviceVendor, error) {
	var vendors []DeviceVendor
	err := Db.Debug().Model(&c).Select("id, parent_id, vendor_value").
		Where(" vendor_type = 1 and device_type = ? and is_deleted = 0 and tenant_id = ?", c.DeviceType, c.TenantId).
		Find(&vendors).Error
	return vendors, err
}

func (c *DeviceVendor) GetBrand() ([]DeviceVendor, error) {
	var vendors []DeviceVendor
	err := Db.Debug().Model(&c).Select("id, parent_id, vendor_value").
		Where(" vendor_type = 2 and device_type = ? and is_deleted = 0 and tenant_id = ?", c.DeviceType, c.TenantId).Find(&vendors).Error
	return vendors, err
}

func (c *DeviceVendor) GetModel() ([]DeviceVendor, error) {
	var vendors []DeviceVendor
	if c.ParentId > 0 {
		err := Db.Debug().Model(&c).Select("id, parent_id, vendor_value").
			Where(" vendor_type = 3 and device_type = ? and is_deleted = 0 and tenant_id = ? and parent_id = ?",
				c.DeviceType, c.TenantId, c.ParentId).Find(&vendors).Error
		return vendors, err
	} else {
		err := Db.Debug().Model(&c).Select("id, parent_id, vendor_value").
			Where(" vendor_type = 3 and device_type = ? and is_deleted = 0 and tenant_id = ?", c.DeviceType, c.TenantId).Find(&vendors).Error
		return vendors, err
	}

}

func (c DeviceVendor) GetDeviceVendors(offset, limit int) ([]DeviceVendor, int64, error) {
	var devices []DeviceVendor
	var count int64
	db := Db.Debug().Model(&c).Where("is_deleted=0")
	if c.VendorValue != "" {
		db.Where("vendor_value like ? ", "%"+c.VendorValue+"%")
	}

	if c.DeviceType >= 0 {
		db.Where("device_type=? ", c.DeviceType)
	}
	db.Count(&count)
	err := db.Order("id desc").Find(&devices).Error
	return devices, count, err
}

func (c DeviceVendor) Remove() error {
	return Db.Debug().Model(&c).Where("id=?", c.ID).Update("is_delete", 1).Error
}
