package com.bonus.auth.controller;

import javax.servlet.http.HttpServletRequest;

import com.bonus.common.core.constant.BusinessConstants;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.utils.global.SystemGlobal;
import com.bonus.system.api.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.bonus.auth.form.LoginBody;
import com.bonus.auth.form.RegisterBody;
import com.bonus.auth.service.SysLoginService;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.JwtUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.security.auth.AuthUtil;
import com.bonus.common.security.service.TokenService;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.model.LoginUser;

import java.util.HashMap;
import java.util.Map;

/**
 * token 控制
 * 
 * @author bonus
 */
@RestController
@Slf4j
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RemoteUserService remoteUserService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }
    @PostMapping("login2")
    public R<?> login2(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("appLogin")
    public R<?> appLogin(@RequestBody LoginBody form) {
        Map<String, Object> map = new HashMap<>(3);
        // APP用户登录
        LoginUser userInfo = sysLoginService.appLogin(form.getUsername(), form.getPassword());
        Map<String, Object> tokenMap = tokenService.createToken(userInfo);
        map.put("access_token",tokenMap.get("access_token"));
        map.put("expires_in",tokenMap.get("expires_in"));
        // 获取app菜单
        R result = remoteUserService.getAppRouters(userInfo.getSysUser().getUserId(), SecurityConstants.INNER);
        if(result.getCode() == BusinessConstants.SUCCESS_CODE){
            map.put("menuList",result.getData());
        }
        // 获取APP用户信息
        R result2 = remoteUserService.getAppUserInfo(userInfo.getSysUser().getUserId(), SecurityConstants.INNER);
        if(result2.getCode() == BusinessConstants.SUCCESS_CODE){
            Map<String, Object> userMap = (Map<String, Object>) result2.getData();
            map.put("user",userMap.get("user"));
            map.put("roles",userMap.get("roles"));
            map.put("permissions",userMap.get("permissions"));
        }
        // 获取登录token
        return R.ok(map);
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        try{
            String token = SecurityUtils.getToken(request);
            if (StringUtils.isNotEmpty(token) && !SystemGlobal.undefined.equals(token.toLowerCase()))
            {
                String username = JwtUtils.getUserName(token);
                String userId= JwtUtils.getUserId(token);
                // 删除用户缓存记录
                AuthUtil.logoutByToken(token);
                // 记录用户退出日志
                sysLoginService.logout(username,userId);
            }
        }catch (Exception e){
            sysLoginService.logout("","");
            log.error(e.toString(),e);
        }
        return R.ok();
    }

    @PostMapping("appLogout")
    public R<?> appLogout(HttpServletRequest request) {
        try{
            String token = SecurityUtils.getToken(request);
            if (StringUtils.isNotEmpty(token) && !SystemGlobal.undefined.equals(token.toLowerCase()))
            {
                String username = JwtUtils.getUserName(token);
                String userId= JwtUtils.getUserId(token);
                // 删除用户缓存记录
                AuthUtil.logoutByToken(token);
                // 记录用户退出日志
                sysLoginService.logout(username,userId);
            }
        }catch (Exception e){
            sysLoginService.logout("","");
            log.error(e.toString(),e);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}
