package dao

import (
	"enterprise/common/model"
	"gorm.io/gorm"
	"time"
)

type CheckinMoneyDao struct {
}

func NewCheckinMoneyDao() *CheckinMoneyDao {
	return &CheckinMoneyDao{}
}

func (d *CheckinMoneyDao) TableName() string {
	return "checkin_money"
}

func (d *CheckinMoneyDao) Create(o *model.CheckinMoney) (int64, error) {
	o.CreateTime = time.Now().Unix()
	res := GetDB().Table(d.TableName()).Create(o)
	return o.Id, res.Error
}

func (d *CheckinMoneyDao) Update(o *model.CheckinMoney) error {
	o.UpdateTime = time.Now().Unix()
	tx := GetDB().Table(d.TableName())
	res := tx.Save(o)
	return res.Error
}

func (d *CheckinMoneyDao) Delete(id int64) error {
	res := GetDB().Table(d.TableName()).Delete(&model.CheckinMoney{}, id)
	return res.Error
}

func (d *CheckinMoneyDao) Get(id int64) (*model.CheckinMoney, error) {
	var u model.CheckinMoney
	tx := GetDB().Table(d.TableName())
	tx = tx.Where("id = ?", id)
	res := tx.First(&u)
	if res.Error == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if res.Error != nil {
		return nil, res.Error
	}
	return &u, nil
}

func (d *CheckinMoneyDao) GetByDay(userId, day, checkinType string) (*model.CheckinMoney, error) {
	var u model.CheckinMoney
	tx := GetDB().Table(d.TableName())
	tx = tx.Where("username = ?", userId)
	tx = tx.Where("checkin_type = ?", checkinType)
	tx = tx.Where("day = ?", day)
	res := tx.First(&u)
	if res.Error == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if res.Error != nil {
		return nil, res.Error
	}
	return &u, nil
}