// Package mapper 数据访问层
package mapper

import (
	"server/config"
	"server/modules/system/entity"
)

type SysUserMapper struct{}

func NewSysUserMapper() *SysUserMapper {
	return &SysUserMapper{}
}

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

func (m *SysUserMapper) FindByID(id string) (*entity.SysUser, error) {
	var item entity.SysUser
	err := config.DB.First(&item, "id = ? AND del_flag = 0", id).Error
	return &item, err
}

func (m *SysUserMapper) FindByUsername(username string) (*entity.SysUser, error) {
	var item entity.SysUser
	err := config.DB.First(&item, "username = ? AND del_flag = 0", username).Error
	return &item, err
}

func (m *SysUserMapper) FindByPhone(phone string) (*entity.SysUser, error) {
	var item entity.SysUser
	err := config.DB.First(&item, "phone = ? AND del_flag = 0", phone).Error
	return &item, err
}

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

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

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

func (m *SysUserMapper) Delete(id string) error {
	// 逻辑删除
	return config.DB.Model(&entity.SysUser{}).Where("id = ?", id).Update("del_flag", 1).Error
}
