package controller

import (
	commonConstants "be.ems/src/framework/constants/common"
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/utils/regular"
	"be.ems/src/framework/vo/result"
	commonModel "be.ems/src/modules/common/model"
	commonService "be.ems/src/modules/common/service"
	systemService "be.ems/src/modules/system/service"

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

// 实例化控制层 RegisterController 结构体
var NewRegister = &RegisterController{
	registerService:    commonService.NewRegisterImpl,
	sysLogLoginService: systemService.NewSysLogLoginImpl,
}

// 账号注册操作处理
//
// PATH /
type RegisterController struct {
	// 账号注册操作服务
	registerService commonService.IRegister
	// 系统登录访问
	sysLogLoginService systemService.ISysLogLogin
}

// 账号注册
//
// GET /register
func (s *RegisterController) Register(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var registerBody commonModel.RegisterBody
	if err := c.ShouldBindJSON(&registerBody); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 判断必传参数
	if !regular.ValidUsername(registerBody.Username) {
		// 账号不能以数字开头，可包含大写小写字母，数字，且不少于5位
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "register.errUsername")))
		return
	}
	if !regular.ValidPassword(registerBody.Password) {
		// 登录密码至少包含大小写字母、数字、特殊符号，且不少于6位
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "register.errPasswd")))
		return
	}
	if registerBody.Password != registerBody.ConfirmPassword {
		// 用户确认输入密码不一致
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "register.errPasswdNotEq")))
		return
	}

	// 当前请求信息
	ipaddr, location := ctx.IPAddrLocation(c)
	os, browser := ctx.UaOsBrowser(c)

	// 校验验证码
	err := s.registerService.ValidateCaptcha(
		registerBody.Code,
		registerBody.UUID,
	)
	// 根据错误信息，创建系统访问记录
	if err != nil {
		s.sysLogLoginService.CreateSysLogLogin(
			registerBody.Username, commonConstants.STATUS_NO, err.Error(),
			ipaddr, location, os, browser,
		)
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	userID, err := s.registerService.ByUserName(registerBody.Username, registerBody.Password, registerBody.UserType)
	if err == nil {
		msg := i18n.TTemplate(language, "register.successMsg", map[string]any{"name": registerBody.Username, "id": userID})
		s.sysLogLoginService.CreateSysLogLogin(
			registerBody.Username, commonConstants.STATUS_YES, msg,
			ipaddr, location, os, browser,
		)
		// 注册成功
		c.JSON(200, result.OkMsg(i18n.TKey(language, "register.success")))
		return
	}
	c.JSON(200, result.ErrMsg(err.Error()))
}
