package dao

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

type ApprovalPaymentDao struct {
}

func NewApprovalPaymentDao() *ApprovalPaymentDao {
	return &ApprovalPaymentDao{}
}

func (d *ApprovalPaymentDao) TableName() string {
	return "approval_payment"
}

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

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

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

func (d *ApprovalPaymentDao) Get(id int64) (*model.ApprovalPayment, error) {
	var u model.ApprovalPayment
	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 *ApprovalPaymentDao) GetBySpNo(spNo string) (*model.ApprovalPayment, error) {
	var u model.ApprovalPayment
	tx := GetDB().Table(d.TableName())
	tx = tx.Where("sp_no = ?", spNo)
	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 *ApprovalPaymentDao) GetByUsername(username, month string) ([]*model.ApprovalPayment, error) {
	var u []*model.ApprovalPayment
	tx := GetDB().Table(d.TableName())
	tx = tx.Where("month = ?", month)
	tx = tx.Where("username = ?", username)
	res := tx.Find(&u)
	if res.Error != nil {
		return nil, res.Error
	}
	return u, nil
}