package controller

import (
	"be.ems/src/framework/config"
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	systemModelVO "be.ems/src/modules/system/model/vo"

	"github.com/gin-gonic/gin"
)

// Me 登录用户信息
//
// GET /me
//
//	@Tags			common/authorization
//	@Accept			json
//	@Produce		json
//	@Success		200	{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Login User Information
//	@Description	Login User Information
//	@Router			/me [get]
func (s AccountController) Me(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	info, err := reqctx.LoginUser(c)
	if err != nil {
		c.JSON(401, resp.CodeMsg(resp.CODE_AUTH_INVALID, err.Error()))
		return
	}

	// 角色权限集合，系统管理员拥有所有权限
	isSystemUser := config.IsSystemUser(info.UserId)
	roles, perms := s.accountService.RoleAndMenuPerms(info.UserId, isSystemUser)

	info.User.NickName = i18n.TKey(language, info.User.NickName)
	info.User.Remark = i18n.TKey(language, info.User.Remark)
	if info.User.Dept != nil {
		info.User.Dept.DeptName = i18n.TKey(language, info.User.Dept.DeptName)
	}
	for ri := range info.User.Roles {
		info.User.Roles[ri].RoleName = i18n.TKey(language, info.User.Roles[ri].RoleName)
	}

	data := map[string]any{
		"user":        info.User,
		"roles":       roles,
		"permissions": perms,
	}
	if !isSystemUser {
		// 强制改密码
		forcePasswdChange, _ := s.accountService.PasswordCountOrExpireTime(info.User.LoginCount, info.User.PasswordUpdateTime)
		if forcePasswdChange {
			data["forcePasswdChange"] = true
		}
	}
	c.JSON(200, resp.OkData(data))
}

// Router 登录用户路由信息
//
// GET /router
//
//	@Tags			common/authorization
//	@Accept			json
//	@Produce		json
//	@Success		200	{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Login User Routing Information
//	@Description	Login User Routing Information
//	@Router			/router [get]
func (s AccountController) Router(c *gin.Context) {
	loginUserId := reqctx.LoginUserToUserID(c)

	// 前端路由，系统管理员拥有所有
	isSystemUser := config.IsSystemUser(loginUserId)
	buildMenus := s.accountService.RouteMenus(loginUserId, isSystemUser)
	// 闭包函数处理多语言
	language := reqctx.AcceptLanguage(c)
	var converI18n func(language string, arr *[]systemModelVO.Router)
	converI18n = func(language string, arr *[]systemModelVO.Router) {
		for i := range *arr {
			(*arr)[i].Meta.Title = i18n.TKey(language, (*arr)[i].Meta.Title)
			if len((*arr)[i].Children) > 0 {
				converI18n(language, &(*arr)[i].Children)
			}
		}
	}
	converI18n(language, &buildMenus)

	c.JSON(200, resp.OkData(buildMenus))
}
