package user

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

type UsersTreeService struct {
}

// CreateUsersTree 创建UsersTree记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersTreeService *UsersTreeService) CreateUsersTree(usersTree user.UsersTree) (err error) {
	err = global.GVA_DB.Create(&usersTree).Error
	return err
}

// DeleteUsersTree 删除UsersTree记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersTreeService *UsersTreeService)DeleteUsersTree(usersTree user.UsersTree) (err error) {
	err = global.GVA_DB.Delete(&usersTree).Error
	return err
}

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

// UpdateUsersTree 更新UsersTree记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersTreeService *UsersTreeService)UpdateUsersTree(usersTree user.UsersTree) (err error) {
	err = global.GVA_DB.Save(&usersTree).Error
	return err
}

// GetUsersTree 根据id获取UsersTree记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersTreeService *UsersTreeService)GetUsersTree(id uint) (usersTree user.UsersTree, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&usersTree).Error
	return
}

// GetUsersTreeInfoList 分页获取UsersTree记录
// Author [piexlmax](https://github.com/piexlmax)
func (usersTreeService *UsersTreeService)GetUsersTreeInfoList(info userReq.UsersTreeSearch) (list []user.UsersTree, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&user.UsersTree{})
    var usersTrees []user.UsersTree
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
    if info.InviterId != nil {
        db = db.Where("inviter_id = ?",info.InviterId)
    }
    if info.TopId != nil {
        db = db.Where("top_id = ?",info.TopId)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

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