package org.nl.hand.rest;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.nl.common.exception.BadRequestException;
import org.nl.common.utils.RsaUtils;
import org.nl.common.utils.dto.CurrentUser;
import org.nl.config.RsaProperties;
import org.nl.system.service.role.ISysRoleService;
import org.nl.system.service.secutiry.dto.AuthUserDto;
import org.nl.system.service.user.ISysUserService;
import org.nl.system.service.user.dao.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
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.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author : TuQiang
 * @create 2024/4/2 16:00
 */
@Slf4j
@RestController
@RequestMapping("/mobile/auth")
public class MobileAuthorizationController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;

    @PostMapping(value = "/login")
    @SaIgnore
    public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception {
        // 密码解密 - 前端的加密规则: encrypt（根据实际更改）
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword());
        // 校验数据库
        // 根据用户名查询，在比对密码
        // 拿到多个已经抛出异常
        SysUser userInfo = userService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, authUser.getUsername()));
        // 这里需要密码加密
        if (ObjectUtil.isEmpty(userInfo) || !userInfo.getPassword().equals(SaSecureUtil.md5BySalt(password, "salt"))) {
            throw new BadRequestException("账号或密码错误！");
        }
        // 获取权限列表 - 登录查找权限
        List<String> permissionList = roleService.getPermissionList((JSONObject) JSON.toJSON(userInfo));

        // 登录输入，登出删除
        CurrentUser user = new CurrentUser();
        user.setId(userInfo.getUser_id());
        user.setUsername(userInfo.getUsername());
        user.setPresonName(userInfo.getPerson_name());
        user.setUser(userInfo);
        user.setPermissions(permissionList);

        // SaLoginModel 配置登录相关参数
        StpUtil.login(userInfo.getUser_id(), new SaLoginModel()
                // 此次登录的客户端设备类型, 用于[同端互斥登录]时指定此次登录的设备类型
                .setDevice("PE")
                // Token挂载的扩展参数 （此方法只有在集成jwt插件时才会生效）
                .setExtra("loginInfo", user)
        );

        // 返回 token 与 用户信息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user", userInfo);
        JSONObject authInfo = new JSONObject(2) {{
            put("token", "Bearer " + StpUtil.getTokenValue());
            put("user", jsonObject);
        }};

        return ResponseEntity.ok(authInfo);
    }
}
