package com.hzs.system.login.controller;

import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.system.sys.SysUser;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.system.login.param.FreeLoginParam;
import com.hzs.system.login.service.IUserLoginService;
import com.hzs.system.sys.dto.LoginUser;
import com.hzs.system.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @Description: 免密登录控制器
 * @Author: jiang chao
 * @Time: 2024/11/5 11:01
 * @Classname: FreeLoginController
 * @PackageName: com.hzs.system.login.controller
 */
@RequestMapping("/manage/user")
@RestController
public class FreeLoginController {

    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private IUserLoginService iUserLoginService;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 免密登录
     *
     * @param param
     * @return
     */
    @PostMapping("/free-login")
    public AjaxResult freeLogin(@Valid @RequestBody FreeLoginParam param) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            return AjaxResult.error("当前用户无权限操作");
        }

        SysUser sysUser = iSysUserService.selectUserById(param.getUserId());
        if (null == sysUser) {
            return AjaxResult.error("管理员不存在");
        }

        // 用户登录
        LoginUser loginUser = iUserLoginService.freeLogin(sysUser.getUserName());

        // 获取登录token
        return AjaxResult.success(userTokenService.createToken(loginUser));
    }

}
