package models

import (
	"errors"

	"git.apinb.com/bsm-sdk/core/database"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/ops/sample/internal/impl"
	"gorm.io/gorm"
)

/*
 * SampleDemo
 * Comment: 示例数据表
 * Version: 10
 * Created: 2022-04-12 10:44:51 , Updated:0001-01-01 00:00:00
 */
type SampleDemo struct {
	types.Std_IICUDS
	Name string `gorm:"column:name;type:varchar(255);default:'';" json:"name"` // 名称
	Age  int    `gorm:"column:age;type:int;default:0;" json:"age"`             // 年龄
}

func init() {
	database.AppendMigrate(&SampleDemo{})
}

// TableName .
func (table *SampleDemo) TableName() string {
	return "sample_demo" //对应数据库表名
}

// GetSampleDemoByField 根据特定字段值获取 SampleDemo 对象
func GetSampleDemoByField(field string, value any) (*SampleDemo, error) {
	var (
		data      SampleDemo
		condition = map[string]any{field: value}
	)
	err := impl.DBService.Where(condition).First(&data).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errcode.ErrRecordNotFound
		}
		return nil, errcode.ErrDB
	}

	return &data, nil
}

func CreateSampleDemo(data *SampleDemo) error {
	if err := impl.DBService.Create(data).Error; err != nil {
		return errcode.ErrDB
	}
	return nil
}

func ListSampleDemos(page, size int) ([]SampleDemo, int64, error) {
	var (
		list  []SampleDemo
		total int64
	)
	db := impl.DBService.Model(&SampleDemo{})
	if err := db.Count(&total).Error; err != nil {
		return nil, 0, errcode.ErrDB
	}
	offset := (page - 1) * size
	if err := db.Order("id desc").Offset(offset).Limit(size).Find(&list).Error; err != nil {
		return nil, 0, errcode.ErrDB
	}
	return list, total, nil
}

func UpdateSampleDemo(data *SampleDemo) error {
	if err := impl.DBService.Save(data).Error; err != nil {
		return errcode.ErrDB
	}
	return nil
}

func DeleteSampleDemo(data *SampleDemo) error {
	if err := impl.DBService.Delete(data).Error; err != nil {
		return errcode.ErrDB
	}
	return nil
}
