
package org.nl.system.controller.secutiry;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.nl.common.utils.RedisUtils;
import org.nl.common.utils.SecurityUtils;
import org.nl.common.utils.dto.CurrentUser;
import org.nl.common.security.config.bean.LoginCodeEnum;
import org.nl.common.security.config.bean.LoginProperties;
import org.nl.system.service.secutiry.impl.OnlineUserService;
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.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Zheng Jie
 * @date 2018-11-23
 * 授权、根据token获取用户详细信息
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@Api(tags = "系统：系统授权接口")
public class AuthorizationController {
    @Autowired
    private  RedisUtils redisUtils;
    @Autowired
    private OnlineUserService onlineUserService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private LoginProperties loginProperties;

    @ApiOperation("登录授权")
    @PostMapping(value = "/login")
    public ResponseEntity<Object> login(@RequestBody Map authMap) throws Exception {
        if (ObjectUtil.isEmpty(authMap)){
          return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(onlineUserService.login(authMap));
    }


    @ApiOperation("获取用户信息")
    @GetMapping(value = "/info")
    public ResponseEntity<Object> getUserInfo() {
        CurrentUser currentUser = SecurityUtils.getCurrentUser();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("roles", SecurityUtils.getCurrentUserPermissions());
        jsonObject.put("user", currentUser.getUser());
        return ResponseEntity.ok(jsonObject);
    }

    @ApiOperation("获取指定用户信息")
    @GetMapping(value = "/userInfo")
    public ResponseEntity<Object> getUserInfo(Long loginId) {
        if (loginId != null){
            SysUser user = userService.getById(loginId);
            return ResponseEntity.ok(user);
        }
        return ResponseEntity.noContent().build();
    }

    @ApiOperation("获取验证码")
    @GetMapping(value = "/code")
    public ResponseEntity<Object> getCode() {
        // 获取运算的结果
        Captcha captcha = loginProperties.getCaptcha();
        String uuid = IdUtil.simpleUUID();
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == LoginCodeEnum.arithmetic.ordinal() && captchaValue.contains(".")) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        // 保存
        redisUtils.set(uuid, captchaValue, loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return ResponseEntity.ok(imgResult);
    }

    @ApiOperation("退出登录")
    @DeleteMapping(value = "/logout")
    public ResponseEntity<Object> logout(HttpServletRequest request) {
        if (ObjectUtil.isNotEmpty(StpUtil.getTokenValue())) {
            onlineUserService.logout(StpUtil.getTokenValue());
        }
        StpUtil.logout();
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
