package models

import "github.com/jinzhu/gorm"

func UpdateBlock(rt *RaspMinerTxs,rs *RaspMinerStat) error {
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}
	var prev RaspMinerStat
	var res RaspMinerTxs
	err := tx.Model(&RaspMinerStat{}).Where(&RaspMinerStat{Addr:rs.Addr}).First(&prev).Error
	if err != nil {
		//不存在创建
		if err == gorm.ErrRecordNotFound {
			if err := tx.Create(&rs).Error;err != nil {
				tx.Rollback()
				return err
			}
		} else {
			tx.Rollback()
			return err
		}
	} else {
		//存在 则更新状态
		if err := tx.Model(&RaspMinerStat{}).Where("Addr = ? ",rs.Addr).Update(&RaspMinerStat{
			MinedAmount:prev.MinedAmount+rs.MinedAmount,
			MinedTicketCount:prev.MinedTicketCount+rs.MinedTicketCount,
			MiningTicketCount:prev.MiningTicketCount+rs.MiningTicketCount,
			Height:rs.Time,
			Time:rs.Time,
		}).Error;err != nil {
			tx.Rollback()
			return err
		}
	}

	if err := tx.Where(&RaspMinerTxs{Height:rt.Height}).Assign(&rt).FirstOrCreate(&res).Error;err != nil {
		tx.Rollback()
		return err
	}

	if err := tx.Model(&RaspConfig{}).Where("config = ? ","height").Update("Height",rt.Height).Error;err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}
