package dao

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

type CorpDao struct {
}

func NewCorpDao() *CorpDao {
	return &CorpDao{}
}

func (d *CorpDao) TableName() string {
	return "corp"
}

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

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

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

func (d *CorpDao) Get(id int64) (*model.Corp, error) {
	var u model.Corp
	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 *CorpDao) GetByHost(host string) (*model.Corp, error) {
	var u model.Corp
	tx := GetDB().Table(d.TableName())
	tx = tx.Where("host LIKE ?", fmt.Sprintf("%%%s%%", host))
	res := tx.First(&u)
	if res.Error == gorm.ErrRecordNotFound {
		return nil, nil
	}

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