package user

import (
	"courseSign/server/global"
	"courseSign/server/model/user"
	"courseSign/server/model/common/request"
    userReq "courseSign/server/model/user/request"
)

type UsersService struct {
}

// CreateUsers 创建Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService) CreateUsers(users user.Users) (err error) {
	err = global.GVA_DB.Create(&users).Error
	return err
}

// DeleteUsers 删除Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)DeleteUsers(users user.Users) (err error) {
	err = global.GVA_DB.Delete(&users).Error
	return err
}

// DeleteUsersByIds 批量删除Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)DeleteUsersByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]user.Users{},"id in ?",ids.Ids).Error
	return err
}

// UpdateUsers 更新Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)UpdateUsers(users user.Users) (err error) {
	err = global.GVA_DB.Save(&users).Error
	return err
}

// GetUsers 根据id获取Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)GetUsers(id uint) (users user.Users, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&users).Error
	return
}

// GetUsersInfoList 分页获取Users记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersService *UsersService)GetUsersInfoList(info userReq.UsersSearch) (list []user.Users, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&user.Users{})
    var userss []user.Users
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
    if info.Address != "" {
        db = db.Where("address = ?",info.Address)
    }
    if info.AddressType != nil {
        db = db.Where("address_type = ?",info.AddressType)
    }
    if info.IsBlack != nil {
        db = db.Where("is_black = ?",info.IsBlack)
    }
    if info.CreateTime != nil {
        db = db.Where("create_time <> ?",info.CreateTime)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

	err = db.Limit(limit).Offset(offset).Find(&userss).Error
	return  userss, total, err
}
