// Package mapper 数据访问层
package mapper

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

	"gorm.io/gorm/clause"
)

type YxHistoryMajorEnrollMapper struct{}

func NewYxHistoryMajorEnrollMapper() *YxHistoryMajorEnrollMapper {
	return &YxHistoryMajorEnrollMapper{}
}

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

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

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

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

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

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

func (m *YxHistoryMajorEnrollMapper) FindByYear(year string) ([]entity.YxHistoryMajorEnroll, error) {
	var items []entity.YxHistoryMajorEnroll
	err := config.DB.Where("year = ?", year).Find(&items).Error
	return items, err
}

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

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

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

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