// Package mapper 数据访问层
package mapper

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

	"gorm.io/gorm/clause"
)

type YxVolunteerMapper struct{}

func NewYxVolunteerMapper() *YxVolunteerMapper {
	return &YxVolunteerMapper{}
}

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

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

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

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

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

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

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

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

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

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