package com.ruoyi.framework.web.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.framework.config.properties.TokenProperties;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.zhdd.feign.FeignUserManageService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * token验证处理
 *
 * @author Lion Li
 */
@Component
@Slf4j
public class TokenService {

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private TokenProperties tokenProperties;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private FeignUserManageService feignUserManageService;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    @SneakyThrows
    public LoginUser getLoginUser(HttpServletRequest request) {
        /*String userStr = request.getHeader("user");
        if (StrUtil.isNotBlank(userStr)) {
            userStr = URLDecoder.decode(userStr, "UTF-8");
            JSONObject userJsonObject = JSONUtil.parseObj(userStr);
            JSONObject principalObject = userJsonObject.getJSONObject("principal");
            String id = userJsonObject.getStr("id");
            log.info("userJsonObject:{}", userJsonObject);
            log.info("principalObject:{}", principalObject);
            // 先从缓存中获取
            String userKey = getTokenKey(id);
            LoginUser user = RedisUtils.getCacheObject(userKey);
            if (user != null) {
                return user;
            }
            // 如果缓存中没有的话，则先查询我们的数据库是否存在，如果不存在则查询四维用户是否存在
            SysUser sysUser = userService.selectUserById(id);
            if (sysUser != null) {
                if (StrUtil.isBlank(sysUser.getDeptId())) {
                    throw new ServiceException("请联系应急事件处置系统管理员分配组织", 90000);
                }
                // 查询当前用户角色
                SysUser userRole = new SysUser();
                userRole.setUserId(id);
                Set<String> roles = permissionService.getRolePermission(userRole);
                if (roles.isEmpty()) {
                    throw new AuthenticationServiceException("请联系应急事件处置系统管理员分配权限");
                }
                user = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
                user.setUserRole(roles.iterator().next());
                setUserAgent(user);
                user.setSuQian(true);
                RedisUtils.setCacheObject(userKey, user, tokenProperties.getExpireTime(), TimeUnit.MINUTES);
                return user;
            }
            // 查询四维用户
            GatewayUserDetail gatewayUserDetail = feignUserManageService.userDetail(id);
            log.info("四维用户详情：{}", gatewayUserDetail);
            throw new AuthenticationServiceException("请联系应急事件处置系统管理员分配组织及权限");


                *//*GatewayUser userDTO = new GatewayUser();
                userDTO.setUserId(id);
                userDTO.setUserGroupId(userJsonObject.getStr("user_group_id"));
                if (principalObject != null) {
                    userDTO.setUsername(principalObject.getStr("userName"));
                    userDTO.setOrgId(principalObject.getStr("orgId"));
                    userDTO.setOrgName(principalObject.getStr("orgName"));
                    userDTO.setRoles(Convert.toList(String.class, principalObject.get("permissions")));
                }
                log.info("当前网关请求用户：{}", userDTO);
                SysUser sysUser = new SysUser();
                sysUser.setUserId(userDTO.getUserId());
                sysUser.setUserName(userDTO.getUsername());
                sysUser.setUserType(userDTO.getUserGroupId());
                LoginUser loginUser = new LoginUser();
                loginUser.setUserId(userDTO.getUserId());
                loginUser.setDeptId(userDTO.getOrgId());
                loginUser.setUser(sysUser);
                loginUser.setSuQian(true);
                return loginUser;*//*
        }*/
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                LoginUser user = RedisUtils.getCacheObject(userKey);
                return user;
            } catch (Exception e) {

            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            RedisUtils.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        String token = IdUtil.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + tokenProperties.getExpireTime() * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        RedisUtils.setCacheObject(userKey, loginUser, tokenProperties.getExpireTime(), TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = ServletUtils.getClientIP();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOs().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
            .setClaims(claims)
            .signWith(SignatureAlgorithm.HS512, tokenProperties.getSecret()).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
            .setSigningKey(tokenProperties.getSecret())
            .parseClaimsJws(token)
            .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(tokenProperties.getHeader());
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }
}
