// 模块模型操作接口-用户
// 秒寻科技
// zt 2024-01-04

package userlogic

import (
	"errors"
	"ipsomc/core/dao/redis/redisapi"
	"ipsomc/core/dao/redis/redismodel"
	"ipsomc/core/user/userapi"
	"ipsomc/core/user/usermodel"
	"ipsomc/util"
	"strconv"
	"time"
)

type UserLgc struct {
	userApi  userapi.UserApi
	redisApi redisapi.RedisApi
}

// 用户登录
func (obj *UserLgc) OperatorLogin(dataModel *usermodel.Operator, respModel *usermodel.RspOperator) error {
	redisModel := new(redismodel.RedisOperator)

	//判断用户名和密码是否正确
	if err := obj.userApi.CheckOperatorRegister(dataModel); err != nil {
		return errors.New("账号或密码错误")
	}

	//生成用户token
	uuid := util.GenerateUuid()
	token := "ptoken" + strconv.Itoa(int(dataModel.ID)) + "-" + uuid

	//缓存用户信息
	redisModel.CompanyID = dataModel.CompanyID
	redisModel.CompanyName = dataModel.CompanyName
	redisModel.ProjectID = dataModel.ProjectID
	redisModel.UserTypeID = int(dataModel.UserTypeID)
	redisModel.UserID = dataModel.ID
	redisModel.UserName = dataModel.UserName
	redisModel.Nickname = dataModel.Nickname
	redisModel.Token = token
	redisModel.TokenTime = time.Now().Format("2006-01-02 15:16:17")

	//生产token过期时间
	myViper := util.GetViper()
	expireTime := myViper.GetInt("token.pc_expire")
	if expireTime <= 0 {
		expireTime = 10 //10分钟
	}

	//以用户的token为键，将用户登录资料保存到redis中
	if err := obj.redisApi.SetModelData(token, redisModel, uint16(expireTime)); err != nil {
		return err
	}

	//组织返回数据
	respModel.CompanyID = dataModel.CompanyID
	respModel.CompanyName = dataModel.CompanyName
	respModel.ProjectID = dataModel.ProjectID
	respModel.ID = dataModel.ID
	respModel.UserTypeID = dataModel.UserTypeID
	respModel.Nickname = dataModel.Nickname
	respModel.Sex = dataModel.Sex
	respModel.Token = token

	return nil
}

// 获得用户访问权限，包括页面访问权限和按钮访问权限
func (obj *UserLgc) GetOperatorPermissionLgc(dataModel *usermodel.Operator) (usermodel.RspOperatorPermission, error) {
	var permission usermodel.RspOperatorPermission

	//获得用户角色列表
	roleList, err1 := obj.userApi.GetOperatorRoleList(dataModel)
	if err1 != nil {
		return permission, err1
	}

	//获得用户权限列表
	permission, err2 := obj.userApi.GetOperatorPermissionList(roleList)
	if err2 != nil {
		return permission, err2
	}

	return permission, nil
}
