package models

type RaspDevList struct {
	Id int64 `json:"id"`
	Addr string `json:"addr"`
	PaiVersion string `json:"pai_version"`
	UpdateTime int64 `json:"update_time"`
	Height int64 `json:"height"`
	BtyVersion string `json:"bty_version"`
	ExtIp string `json:"ext_ip"`
	Error string `json:"error"`
	WalletStatus int32 `json:"wallet_status"`
	NodeStatus int32 `json:"node_status"`
	PaiStatus int32 `json:"pai_status"`
	UserName string `json:"user_name"`
	Email string `json:"email"`
	Phone string `json:"phone"`
}

type RaspDevListQuery struct {
	Id int64
	Addr string
	Page int64
	PageSize int64
}

func GetDevList(rasp RaspDevListQuery)([]*RaspDevList,error) {
	var list []*RaspDevList
	if err := db.Model(&RaspDevList{}).Where("addr = ? ",rasp.Addr).Limit(rasp.Page).Order("id desc").Find(&list).Error ;err != nil {
		return nil,err
	}
	return list,nil
}

func GetAllDevList() ([]*RaspDevList,error) {
	var list []*RaspDevList
	if err := db.Model(&RaspDevList{}).Find(&list).Error ;err != nil {
		return nil,err
	}
	return list,nil
}

func UpdateDevList(rasp RaspDevList) error {
	var dev RaspDevList
	err := db.Where(RaspDevList{Addr: rasp.Addr}).Assign(rasp).FirstOrCreate(&dev).Error
	if err != nil  {
		return err
	}
	return nil
}

func UpdateDevList1(rasp RaspDevList) error {
	var dev RaspDevList
	tx := db.Begin()
	if tx.Where("addr = ?",rasp.Addr).First(&dev).RecordNotFound() {
		if err :=tx.Create(&rasp).Error;err != nil {
			tx.Rollback()
			return err
		}
		return tx.Commit().Error
	}
	if err :=tx.Model(&dev).Where("addr = ?",rasp.Addr).Updates(
		map[string]interface{}{
			"pai_version":rasp.PaiVersion,
			"update_time":rasp.UpdateTime,
			"height":rasp.Height,
			"bty_version":rasp.BtyVersion,
			"ext_ip":rasp.ExtIp,
			"err":"",
			"wallet_status":rasp.WalletStatus,
			"node_status":rasp.NodeStatus,
			"pai_status":rasp.PaiStatus,
		},
	).Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}