package dao

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

type ApprovalCheckinDao struct {
}

func NewApprovalCheckinDao() *ApprovalCheckinDao {
	return &ApprovalCheckinDao{}
}

func (d *ApprovalCheckinDao) TableName() string {
	return "approval_checkin"
}

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

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

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

func (d *ApprovalCheckinDao) Get(id int64) (*model.ApprovalCheckin, error) {
	var u model.ApprovalCheckin
	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 *ApprovalCheckinDao) GetBySpNo(corpId int64, spNo string) (*model.ApprovalCheckin, error) {
	var u model.ApprovalCheckin
	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 *ApprovalCheckinDao) GetByUsernameMonth(username, month string) ([]*model.ApprovalCheckin, error) {
	var u []*model.ApprovalCheckin
	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
}

func (d *ApprovalCheckinDao) GetByUsernameDay(corpId int64, username, day string) (*model.ApprovalCheckin, error) {
	var u model.ApprovalCheckin
	tx := GetDB().Table(d.TableName())
	tx = tx.Where("checkin_date = ?", day)
	tx = tx.Where("username = ?", username)
	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
}