package com.ruoyi.framework.web.service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.UserEnvConstant;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import static com.ruoyi.common.constant.Constants.*;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService
{
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    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;


    private final static long EXPIRE_TIME_QR = 3 * 60;


    private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;


    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private RedisService redisService;

    @Resource
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        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 = redisCache.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);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser)
    {
        String token = IdUtils.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() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

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

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

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .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(header);
        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;
    }



    /**
     * 生成二维码
     *
     * @return
     */
    public String getQrCode() {
        String uuid = UUID.randomUUID().toString();
        redisService.setCacheObject(uuid, EMPOWER, EXPIRE_TIME_QR, TimeUnit.SECONDS);
        return uuid;
    }


    /**
     * 判断二维码是否被扫描
     *
     * @param uuid
     * @return
     */
    public R<?> getPool(String uuid) {
        R<?> r = new R<>();
        r.setMsg("un_scan");
        if (redisService.getCacheObject(uuid) == null){
            return  r;
        }
        String cacheObject = redisService.getCacheObject(uuid).toString();
        try {
            if (StringUtils.isBlank(cacheObject)) {
                r.setMsg("该二维码已经失效,请重新获取");
            } else if (cacheObject.equals(SUCCESS.toString())) {
                r.setMsg("has_scan");
            } else if (cacheObject.length() > 3) {
                SysUser user = sysUserService.getByPhone(cacheObject.toString());
                LoginUser loginUser = packPermDeptRoles(user);
                //获取token
                Map<String, Object> token = tokenService.createTokenQr(loginUser);
                Object accessToken = token.get("access_token");
                r.setCode(SUCCESS_QR);
                r.setMsg(LOGIN_SUCCESS_APP+accessToken);
                redisCache.deleteObject(uuid);
                return r;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return r;
    }

    private LoginUser packPermDeptRoles(SysUser sysUser) {
        LoginUser sysUserVo = new LoginUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        sysUserVo.setUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return sysUserVo;
    }


    /**
     * 创建令牌
     */
    public Map<String, Object> createTokenQr(LoginUser loginUser) {
        // 生成token
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        loginUser.setUserId(loginUser.getUser().getUserId());
        loginUser.setUserName(loginUser.getUser().getUserName());
        loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));

        JSONObject userEnv = packUserEnv(loginUser);
        loginUser.setUserEnv(userEnv);
        loginUser.setLoginType("PC");
        refreshToken(loginUser);

        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", token);
        map.put("expires_in", EXPIRE_TIME);
        redisService.setCacheObject(ACCESS_TOKEN + token, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
        return map;
    }

    private JSONObject packUserEnv(LoginUser loginUser) {
        JSONObject userEnv = new JSONObject();
        userEnv.put(UserEnvConstant.USER_ID, loginUser.getUserId());
        userEnv.put(UserEnvConstant.USERNAME, loginUser.getUsername());

        SysDept dept = loginUser.getUser().getDept();
        userEnv.put(UserEnvConstant.USER_DEPT_ID, loginUser.getUser().getDeptId());
        userEnv.put(UserEnvConstant.USER_DEPT_NAME, dept.getDeptName());

        Long parentId = dept.getParentId();
        SysDept parentDept = deptService.selectDeptById(parentId);
        if (ObjectUtils.isNotEmpty(parentDept)) {
            userEnv.put(UserEnvConstant.USER_PARENT_DEPT_ID, parentDept.getDeptId());
            userEnv.put(UserEnvConstant.USER_PARENT_DEPT_NAME, parentDept.getDeptName());
        }
        return userEnv;
    }

    /**
     * 用户扫码成功,改变redis中的值
     *
     * @param uuid
     * @return
     */
    public R<String> scanCode(String uuid) {
        R<String> r = new R<>();
        Object code = redisService.getCacheObject(uuid);
        r.setCode(SUCCESS_QR);
        r.setData(uuid);
        if (code == null) {
            r.setCode(FAIL_QR);
            r.setMsg("该二维码已经失效,请重新获取");
        }
        if (code != null) {
            redisService.setCacheObject(uuid, SUCCESS_QR);
        }
        return r;
    }
}
