package service

import (
	"fmt"

	"be.ems/src/framework/config"
	"be.ems/src/framework/constants"
	"be.ems/src/framework/token"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/modules/auth/model"
	systemModel "be.ems/src/modules/system/model"
	systemService "be.ems/src/modules/system/service"
)

// 实例化服务层 Account 结构体
var NewAccount = &Account{
	sysUserService:      systemService.NewSysUser,
	sysConfigService:    systemService.NewSysConfig,
	sysRoleService:      systemService.NewSysRole,
	sysMenuService:      systemService.NewSysMenu,
	sysLogSourceService: systemService.NewSysLoginSource,
}

// 账号身份操作服务 服务层处理
type Account struct {
	sysUserService      *systemService.SysUser        // 用户信息服务
	sysConfigService    *systemService.SysConfig      // 参数配置服务
	sysRoleService      *systemService.SysRole        // 角色服务
	sysMenuService      *systemService.SysMenu        // 菜单服务
	sysLogSourceService *systemService.SysLoginSource // 认证源
}

// ByUserId 用户ID刷新令牌创建用户信息
func (s Account) ByUserId(userId int64) (token.UserInfo, error) {
	info := token.UserInfo{}

	// 查询用户登录账号
	sysUser := s.sysUserService.FindById(userId)
	if sysUser.UserId != userId {
		return info, fmt.Errorf("user does not exist")
	}
	if sysUser.DelFlag == constants.STATUS_YES {
		return info, fmt.Errorf("sorry, your account has been deleted. Sorry, your account has been deleted")
	}
	if sysUser.StatusFlag == constants.STATUS_NO {
		return info, fmt.Errorf("sorry, your account has been disabled")
	}

	// 登录用户信息
	info.UserId = sysUser.UserId
	info.DeptId = sysUser.DeptId
	info.User = sysUser
	// 用户权限组标识
	if config.IsSystemUser(sysUser.UserId) {
		info.Permissions = []string{constants.SYS_PERMISSION_SYSTEM}
	} else {
		perms := s.sysMenuService.FindPermsByUserId(sysUser.UserId)
		info.Permissions = parse.RemoveDuplicates(perms)
	}
	return info, nil
}

// UpdateLoginDateAndIP 更新登录时间和IP
func (s Account) UpdateLoginDateAndIP(info token.UserInfo) bool {
	user := s.sysUserService.FindById(info.UserId)
	user.Password = "" // 密码不更新
	user.LoginCount += 1
	user.LoginIp = info.LoginIp
	user.LoginTime = info.LoginTime
	return s.sysUserService.Update(user) > 0
}

// LoginSource 登录认证源
func (s Account) LoginSource() []model.LoginSourceVo {
	rows := s.sysLogSourceService.FindByActive("")
	data := make([]model.LoginSourceVo, 0)
	for _, v := range rows {
		data = append(data, model.LoginSourceVo{
			UID:  v.UID,
			Name: v.Name,
			Type: v.Type,
			Icon: v.Icon,
		})
	}
	return data
}

// initLoginSourceUser 初始化登录源用户
func (s *Account) initLoginSourceUser(uid, sType, username, password string) systemModel.SysUser {
	sysUser := systemModel.SysUser{
		UserName:   username,
		NickName:   username, // 昵称使用名称账号
		Password:   password, // 原始密码
		UserType:   sType,
		UserSource: uid,
		Sex:        "0",                  // 性别未选择
		StatusFlag: constants.STATUS_YES, // 账号状态激活
		DeptId:     101,                  // 归属部门为根节点
		CreateBy:   sType,                // 创建来源
	}

	// 新增用户的角色管理
	sysUser.RoleIds = []int64{5}
	// 新增用户的岗位管理
	sysUser.PostIds = []int64{}

	insertId := s.sysUserService.Insert(sysUser)
	if insertId > 0 {
		sysUser.UserId = insertId
	}
	return s.sysUserService.FindByUserName(username, sType, uid)
}
