package dao

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

type ApprovalVacationDao struct {
}

func NewApprovalVacationDao() *ApprovalVacationDao {
	return &ApprovalVacationDao{}
}

func (d *ApprovalVacationDao) TableName() string {
	return "approval_vacation"
}

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

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

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

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

func (d *ApprovalVacationDao) GetByUsernameDay(corpId int64, username, day string) (*model.ApprovalVacation, error) {
	var u model.ApprovalVacation
	tx := GetDB().Table(d.TableName())
	tx = tx.Where("corp_id = ?", corpId)
	tx = tx.Where("vacation_date = ?", day)
	tx = tx.Where("username = ?", username)

	res := tx.First(&u)
	if res.Error == gorm.ErrRecordNotFound {
		return nil, nil
	}

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

	return &u, nil
}