package com.microservices.common.security.service;

import com.microservices.common.core.constant.CacheConstants;
import com.microservices.common.core.constant.SecurityConstants;
import com.microservices.common.core.constant.TokenConstants;
import com.microservices.common.core.utils.JwtUtils;
import com.microservices.common.core.utils.ServletUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.utils.ip.IpUtils;
import com.microservices.common.core.utils.uuid.IdUtils;
import com.microservices.common.redis.service.RedisService;
import com.microservices.common.security.interceptor.HeaderInterceptor;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.system.api.RemoteUserService;
import com.microservices.system.api.domain.SysRole;
import com.microservices.system.api.domain.SysUser;
import com.microservices.system.api.domain.SysUserDeptRole;
import com.microservices.system.api.model.LoginUser;
import com.microservices.system.api.utils.FeignUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author microservices
 */
@Component
public class TokenService {
    private static final Logger logger = LoggerFactory.getLogger(HeaderInterceptor.class);
    @Autowired
    private RedisService redisService;
    @Autowired
    private RemoteUserService remoteUserService;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private final static long expireTime = CacheConstants.EXPIRATION;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    private final static String GITLINK_ACCESS_TOKEN = CacheConstants.GITLINK_ACCESS_TOKEN;

    private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        Long gitLinkUserId = loginUser.getSysUser().getGitlinkUserId();
        String token = null;
        if (gitLinkUserId != null) {
            token = FeignUtils.getReturnData(
                    remoteUserService.getTokenByGitLinkUserId(gitLinkUserId, SecurityConstants.INNER)
            );
        }
        if (StringUtils.isEmpty(token)) {
            token = IdUtils.fastUUID();
        } else {
            loginUser.setCookie(genCookieByToken(token));
        }
        Long userId = loginUser.getSysUser().getUserId();
        String userName = loginUser.getSysUser().getUserName();
        loginUser.setToken(token);
        loginUser.setUserId(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        // 刷新Token
        refreshToken(loginUser);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);

        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        rspMap.put("expires_in", expireTime);
        return rspMap;
    }

    private String genCookieByToken(String token) {
        return String.format("%s%s;", TokenConstants.GitLink_Token_Key, token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token) {
        LoginUser user = null;
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userKey = JwtUtils.getUserKey(token);
                user = redisService.getCacheObject(getTokenKey(userKey));
                return user;
            }
        } catch (Exception e) {
            logger.error("通过token获取用户身份信息发生异常：{0}", e);
        }
        return user;
    }

    /**
     * 通过userKey获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUserByUserKey(String userkey) {
        try {
            if (StringUtils.isNotEmpty(userkey)) {
                return redisService.getCacheObject(getTokenKey(userkey));
            }
        } catch (Exception e) {
            logger.error("通过userKey获取用户身份信息发生异常：{0}", 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 = JwtUtils.getUserKey(token);
            redisService.deleteObject(getTokenKey(userkey));
        }
    }

    /**
     * 验证令牌有效期，相差不足120分钟，自动刷新缓存
     *
     * @param loginUser
     */
    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() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 获取用户身份列表
     */
    public List<SysUserDeptRole> getAllUserIdentity(String userName) {
        return redisService.getCacheObject(CacheConstants.getUserIdentifyListKey(userName));
    }

    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }

    private String getGitLinkTokenKey(String token) {
        return GITLINK_ACCESS_TOKEN + token;
    }

    public void setGitLinkToken(LoginUser loginUser, String token) {
        // 根据uuid将loginUser缓存
        String userKey = getGitLinkTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, token, expireTime, TimeUnit.MINUTES);
    }

    public String getGitLinkToken(String userKey) {
        String token = "";
        if (StringUtils.isNotEmpty(userKey)) {
            token = redisService.getCacheObject(getGitLinkTokenKey(userKey));
            return token;
        }
        return token;
    }

    /**
     * 根据用户id和组织Id获取用户身份
     *
     * @param username 用户名
     * @param deptId   组织Id
     * @return 用户身份
     */
    public SysUserDeptRole getUserIdentify(String username, Long deptId) {
        List<SysUserDeptRole> sysUserDeptRoleList = redisService.getCacheObject(CacheConstants.getUserIdentifyListKey(username));
        if (sysUserDeptRoleList == null) {
            return null;
        }
        if (deptId == null || deptId.equals(0L)) {
            return getFirstUserIdentify(sysUserDeptRoleList);
        }
        return sysUserDeptRoleList
                .stream()
                .filter(x -> x.getDeptId() != null && x.getDeptId().equals(deptId))
                .findFirst()
                .orElse(null);
    }

    private SysUserDeptRole getFirstUserIdentify(List<SysUserDeptRole> sysUserDeptRoleList) {
        // 获取第一个组织和角色都不为空的身份
        return sysUserDeptRoleList.stream()
                .filter(x -> x.getDeptId() != null && x.getRoleId() != null)
                .findFirst()
                .orElse(null);
    }

    public Set<String> getMenuPermissionsByRoleKey(String roleKey) {
        if (StringUtils.isEmpty(roleKey)) {
            return new HashSet<>();
        }
        String redisKey = CacheConstants.getRoleMenuPermissionsKey(roleKey);
        if (redisService.hasKey(redisKey)) {
            return redisService.getCacheSet(redisKey);
        }
        Set<String> menuPermissions = FeignUtils.getReturnData(
                remoteUserService.selectMenuPermissionByRoleKey(roleKey, SecurityConstants.INNER)
        );
        if (menuPermissions == null) {
            menuPermissions = new HashSet<>();
        }
        redisService.setCacheSet(redisKey, menuPermissions);
        return menuPermissions;
    }


    /**
     * 获取当前登录用户角色权限
     *
     * @return 角色权限集合
     */
    public Set<String> getRolePermissions() {
        Set<String> roles = new HashSet<>();
        SysUser user = getSysUserByLoginUser();
        if (user == null) {
            return roles;
        }
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            roles.add("admin");
        }
        SysUserDeptRole userIdentity = SecurityUtils.getUserIdentity();
        if (userIdentity == null || userIdentity.getSysRole() == null) {
            return roles;
        }
        SysRole role = userIdentity.getSysRole();
        roles.add(role.getRoleKey());
        return roles;
    }

    /**
     * 获取当前用户菜单权限
     *
     * @return 菜单权限集合
     */
    public Set<String> getMenuPermissions() {
        Set<String> perms = new HashSet<>();
        SysUser user = getSysUserByLoginUser();
        if (user == null) {
            return perms;
        }
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
        }
        SysUserDeptRole userIdentity = SecurityUtils.getUserIdentity();
        if (userIdentity == null || userIdentity.getSysRole() == null) {
            return perms;
        }
        SysRole role = userIdentity.getSysRole();
        Set<String> rolePerms = getMenuPermissionsByRoleKey(role.getRoleKey());
        role.setPermissions(rolePerms);
        perms.addAll(rolePerms);
        return perms;
    }

    private SysUser getSysUserByLoginUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null || loginUser.getSysUser() == null) {
            return null;
        }
        return loginUser.getSysUser();
    }
}