package user

import (
	"bsm/full/module/base/mgt/internal/impl"
	"bsm/full/module/base/mgt/internal/libs"
	"bsm/full/module/base/mgt/internal/logic/tool"
	"bsm/full/module/base/mgt/internal/models"
	"bsm/full/module/base/mgt/internal/types"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	"github.com/gin-gonic/gin"
)

func Fetch(c *gin.Context) {
	var (
		request       = types.UserRequest{}
		count   int64 = 0
		data          = make([]types.UserResp, 0)
		db            = impl.DBService.Model(&models.MgtUser{})
	)

	// 解析JSON请求
	err := c.ShouldBindJSON(&request)
	if err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}

	// 参数验证
	if err := libs.ValidateStruct(&request); err != nil {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if request.Keyword != "" {
		likeStr := "%" + request.Keyword + "%"
		db = db.Where("name like ? or account like ? or phone like ?", likeStr, likeStr, likeStr)
	}
	if request.Status != 0 {
		db = db.Where("status =  ? ", request.Status)
	}

	page, size := tool.GetSizeAndPage(request.Page, request.Size)
	if err := db.Count(&count).Limit(size).Offset((page - 1) * size).Find(&data).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	infra.Response.Success(c, types.FetchResp{Data: data, Page: page, Size: size, Total: count})
}
