package service

import (
	"entrance-grpc/iam"
	"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.AdminDB).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 = "未知"
	res, err := config.GetIamClient().GetAdminUserByID(ctx, &iam.GetAdminUserByIDReq{
		UID: models.AdminID,
	})
	if err == nil && res.Data != nil {
		models.AdminName = res.Data.UserName
	}

	//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.AdminDB).AdminUser
		m            = q.WithContext(ctx).Where(q.Environment.Eq(os.Getenv("GIN_MODE")))
		offset int64 = 0
		models forms.UserAccountListRes
		lists  []*forms.AdminLogListModel
	)

	roleId, _ := ctx.Get("admin_role_id")

	if !config.IsSuperRole(roleId.(int64)) {
		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)
		}
	}
	uIds := make([]int64, 0)
	for _, v := range lists {
		uIds = append(uIds, v.AdminID)
	}

	resp, err := config.GetIamClient().BatchGetAdminUser(ctx, &iam.BatchGetAdminUserReq{
		UIds: uIds,
	})
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错", err)
	}
	uMaps := make(map[int64]*iam.AdminUserInfo)
	for _, v := range resp.Data {
		uMaps[v.ID] = v
	}
	for _, v := range lists {
		v.AdminName = "未知"
		if _, ok := uMaps[v.AdminID]; ok {
			v.AdminName = uMaps[v.AdminID].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)
}
