// Package mapper 数据访问层
package mapper

import (
	"server/config"
	"server/modules/yx/entity"

	"gorm.io/gorm/clause"
)

type YxVolunteerRecordMapper struct{}

func NewYxVolunteerRecordMapper() *YxVolunteerRecordMapper {
	return &YxVolunteerRecordMapper{}
}

func (m *YxVolunteerRecordMapper) FindAll(page, size int) ([]entity.YxVolunteerRecord, int64, error) {
	var items []entity.YxVolunteerRecord
	var total int64
	config.DB.Model(&entity.YxVolunteerRecord{}).Count(&total)
	err := config.DB.Offset((page - 1) * size).Limit(size).Find(&items).Error
	return items, total, err
}

func (m *YxVolunteerRecordMapper) FindByID(id string) (*entity.YxVolunteerRecord, error) {
	var item entity.YxVolunteerRecord
	err := config.DB.First(&item, "id = ?", id).Error
	return &item, err
}

func (m *YxVolunteerRecordMapper) Create(item *entity.YxVolunteerRecord) error {
	return config.DB.Create(item).Error
}

func (m *YxVolunteerRecordMapper) Update(item *entity.YxVolunteerRecord) error {
	return config.DB.Save(item).Error
}

func (m *YxVolunteerRecordMapper) UpdateFields(id string, fields map[string]interface{}) error {
	return config.DB.Model(&entity.YxVolunteerRecord{}).Where("id = ?", id).Updates(fields).Error
}

func (m *YxVolunteerRecordMapper) Delete(id string) error {
	return config.DB.Delete(&entity.YxVolunteerRecord{}, "id = ?", id).Error
}

func (m *YxVolunteerRecordMapper) BatchCreate(items []entity.YxVolunteerRecord, batchSize int) error {
	return config.DB.CreateInBatches(items, batchSize).Error
}

func (m *YxVolunteerRecordMapper) BatchUpdate(items []entity.YxVolunteerRecord) error {
	return config.DB.Save(items).Error
}

func (m *YxVolunteerRecordMapper) BatchUpsert(items []entity.YxVolunteerRecord, updateColumns []string) error {
	return config.DB.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns(updateColumns),
	}).CreateInBatches(items, 100).Error
}

func (m *YxVolunteerRecordMapper) BatchDelete(ids []string) error {
	return config.DB.Delete(&entity.YxVolunteerRecord{}, "id IN ?", ids).Error
}
