package service

import (
	"fmt"

	"be.ems/src/framework/constants"
	"be.ems/src/framework/database/redis"
	"be.ems/src/framework/utils/parse"
	systemModel "be.ems/src/modules/system/model"
	systemService "be.ems/src/modules/system/service"
)

// 实例化服务层 Register 结构体
var NewRegister = &Register{
	sysUserService:   systemService.NewSysUser,
	sysConfigService: systemService.NewSysConfig,
}

// 账号注册操作处理 服务层处理
type Register struct {
	sysUserService   *systemService.SysUser   // 用户信息服务
	sysConfigService *systemService.SysConfig // 参数配置服务
}

// ValidateCaptcha 校验验证码
func (s Register) ValidateCaptcha(code, uuid string) error {
	// 验证码检查，从数据库配置获取验证码开关 true开启，false关闭
	captchaEnabledStr := s.sysConfigService.FindValueByKey("sys.account.captchaEnabled")
	if !parse.Boolean(captchaEnabledStr) {
		return nil
	}
	if code == "" || uuid == "" {
		return fmt.Errorf("verification code information error")
	}
	verifyKey := constants.CACHE_CAPTCHA_CODE + ":" + uuid
	captcha, err := redis.Get("", verifyKey)
	if err != nil {
		return fmt.Errorf("the verification code has expired")
	}
	redis.Del("", verifyKey)
	if captcha != code {
		return fmt.Errorf("verification code error")
	}
	return nil
}

// ByUserName 账号注册
func (s Register) ByUserName(username, password string) (int64, error) {
	// 是否开启用户注册功能 true开启，false关闭
	registerUserStr := s.sysConfigService.FindValueByKey("sys.account.registerUser")
	captchaEnabled := parse.Boolean(registerUserStr)
	if !captchaEnabled {
		return 0, fmt.Errorf("failed to register user [%s]. Sorry, the system has closed the external user registration channel", username)
	}

	// 检查用户登录账号是否唯一
	uniqueUserName := s.sysUserService.CheckUniqueByUserName(username, 0)
	if !uniqueUserName {
		return 0, fmt.Errorf("failed to register user [%s], registered account already exists", username)
	}

	sysUser := systemModel.SysUser{
		UserName:   username,
		NickName:   username, // 昵称使用名称账号
		Password:   password, // 原始密码
		UserType:   "System",
		UserSource: "#",
		Sex:        "0",                  // 性别未选择
		StatusFlag: constants.STATUS_YES, // 账号状态激活
		DeptId:     101,                  // 归属部门为根节点
		CreateBy:   "System",             // 创建来源
	}

	// 新增用户的角色管理
	sysUser.RoleIds = s.registerRoleInit()
	// 新增用户的岗位管理
	sysUser.PostIds = s.registerPostInit()

	insertId := s.sysUserService.Insert(sysUser)
	if insertId > 0 {
		return insertId, nil
	}
	return 0, fmt.Errorf("failed to register user [%s]. Please contact the GM", username)
}

// registerRoleInit 注册初始角色
func (s Register) registerRoleInit() []int64 {
	return []int64{}
}

// registerPostInit 注册初始岗位
func (s Register) registerPostInit() []int64 {
	return []int64{}
}
