package com.securitycontrol.auth.controller;


import com.securitycontrol.auth.form.LoginBody;
import com.securitycontrol.auth.service.SysLoginService;
import com.securitycontrol.common.core.constant.SecurityConstants;
import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.utils.JwtUtils;
import com.securitycontrol.common.redis.service.RedisService;
import com.securitycontrol.common.security.service.TokenService;
import com.securitycontrol.common.security.utils.SecurityUtils;
import com.securitycontrol.system.api.domain.decision.SysMenu;
import com.securitycontrol.system.api.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * token 控制
 *
 * @author czc
 */
@Api(tags = "系统登录")
@RestController
@Slf4j
public class TokenController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisService redisUtil;

    @Autowired
    private SysLoginService sysLoginService;




    @PostMapping("login")
    public Result<?> login(LoginBody form) {
        List<SysMenu>  menu=null;
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword(),menu);
        // 获取登录token
        return Result.ok(tokenService.createToken(userInfo));
    }



    /**
     * 本地推出登录
     * @param request
     * @return
     */
    @PostMapping("logout")
    public Result<?> loginOut(HttpServletRequest request) {
        String jwtToken = SecurityUtils.getToken(request);
        Claims claims = JwtUtils.parseToken(jwtToken);
        Integer userId = (Integer) claims.get(SecurityConstants.DETAILS_USER_ID);
        String iscUser = (String) claims.get(SecurityConstants.DETAILS_ISC_USER_ID);
        String userName = (String) claims.get(SecurityConstants.DETAILS_USERNAME);
        redisUtil.delete("token:" + jwtToken);
        redisUtil.delete("userId:" + userId);
        redisUtil.delete("ISCUserId:" + iscUser);
        redisUtil.delete("userName:" + userName);
        return Result.ok();
    }










}
