package service

import (
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/forms"
	"gadmin/internal/gorm/query"
	"gadmin/utility/serializer"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
	"os"
)

// AdminLog 后台日志
var AdminLog = new(sAdminLog)

type sAdminLog struct{}

func (s *sAdminLog) View(ctx *gin.Context, req forms.AdminLogViewReq) serializer.Response {
	var (
		q      = query.Use(config.DB).AdminLog
		u      = query.Use(config.DB).AdminUser
		m      = q.WithContext(ctx).Where(q.Environment.Eq(os.Getenv("GIN_MODE")))
		models *forms.AdminLogViewModel
	)

	err := m.Where(q.ID.Eq(req.Id)).Scan(&models)
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 models", err)
	}

	if models == nil {
		return serializer.Err(consts.CodeParamErr, "没有找到数据", nil)
	}

	models.AdminName = "未知"
	user, _ := u.WithContext(ctx).Where(u.ID.Eq(models.AdminID)).First()
	if user != nil {
		models.AdminName = user.UserName
	}

	return serializer.Suc(models)
}

func (s *sAdminLog) List(ctx *gin.Context, req forms.AdminLogListReq) serializer.Response {
	var (
		q            = query.Use(config.DB).AdminLog
		u            = query.Use(config.DB).AdminUser
		m            = q.WithContext(ctx).Where(q.Environment.Eq(os.Getenv("GIN_MODE")))
		offset int64 = 0
		models forms.UserAccountListRes
		lists  []*forms.AdminLogListModel
	)

	if !config.IsSuperRole(User.GetUserRoleId(ctx)) {
		m = m.Where(q.AdminID.Eq(token.GetUID(ctx)))
	}

	if req.AdminId > 0 {
		m = m.Where(q.AdminID.Eq(req.AdminId))
	}

	if req.Path != "" {
		m = m.Where(q.Path.Eq(req.Path))
	}

	if req.Ip != "" {
		m = m.Where(q.AccessIP.Eq(req.Ip))
	}
	if req.Method != "" {
		m = m.Where(q.Method.Eq(req.Method))
	}

	if len(req.CreatedAt) == 2 {
		m = m.Where(q.CreatedAt.Between(req.Time[0], req.Time[1]))
	}

	m = m.Order(q.ID.Desc())

	req.Page, req.PerPage, offset = forms.CalculatePage(req.Page, req.PerPage)

	count, err := m.Count()
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 count", err)
	}

	if count > 0 {
		if err = m.Limit(int(req.PerPage)).Offset(int(offset)).Scan(&lists); err != nil {
			return serializer.Err(consts.CodeParamErr, "查询出错 lists", err)
		}
	}

	for _, v := range lists {
		v.AdminName = "未知"
		user, _ := u.WithContext(ctx).Where(u.ID.Eq(v.AdminID)).First()
		if user != nil {
			v.AdminName = user.UserName
		}

		v.Remark = config.GetMenuName(v.Path)
	}

	models.List = lists
	models.Page = req.Page
	models.PerPage = req.PerPage
	models.PageCount = (count + req.PerPage - 1) / req.PerPage

	return serializer.Suc(models)
}
