package com.bonus.common.security.service;

import cn.hutool.core.util.ObjectUtil;
import com.bonus.common.core.constant.CacheConstants;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.utils.JwtUtils;
import com.bonus.common.core.utils.ServletUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.ip.IpUtils;
import com.bonus.common.core.utils.uuid.IdUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.redis.service.RedisService;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.config.SystemConfig;
import com.bonus.system.api.RemoteConfigService;
import com.bonus.system.api.RemoteUserService;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

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

/**
 * token验证处理
 *
 * @author bonus
 */
@Component
public class TokenService {

    @Resource
    private SystemConfig systemConfig;

    private static final Logger log = LoggerFactory.getLogger(TokenService.class);

    @Autowired
    private RedisService redisService;

    @Resource
    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 LOGIN_USER_KEY = CacheConstants.LOGIN_USER_KEY;

    private final static String LOGIN_STAFF_KEY = CacheConstants.LOGIN_STAFF_KEY;

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

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        // 检查并删除已有的token
        //delExistingToken(loginUser.getSysUser().getUserId());
        String token = IdUtils.fastUUID();
        Long userId = loginUser.getSysUser().getUserId();
        String userName = loginUser.getSysUser().getUserName();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        refreshToken(loginUser);
        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>(16);
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
        String accessToken = JwtUtils.createToken(claimsMap);
        Map<String, Object> rspMap = new HashMap<String, Object>(16);
        rspMap.put("access_token", accessToken);
        rspMap.put("expires_in", EXPIRETIME);
        rspMap.put("isLogin", isLogin(String.valueOf(userId)));
        long tokenTime = getTokenTime();
        //对token进行存储
        redisService.setCacheObject(LOGIN_USER_KEY + userId, token, tokenTime, TimeUnit.MINUTES);
        SysUser sysUser = new SysUser();
        sysUser.setUserId(loginUser.getSysUser().getUserId());
        sysUser.setLoginDate(new Date());
        AjaxResult edit = remoteUserService.systemUpdateUser(sysUser, SecurityConstants.INNER);
        return rspMap;
    }

    public Map<String, Object> createKitchenStaffToken(LoginUser loginUser) {
        // 检查并删除已有的token
        //delExistingToken(loginUser.getSysUser().getUserId());
        String token = IdUtils.fastUUID();
        Long userId = loginUser.getSysUser().getUserId();
        String userName = loginUser.getSysUser().getUserName();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        refreshToken(loginUser);
        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>(16);
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
        String accessToken = JwtUtils.createToken(claimsMap);
        Map<String, Object> rspMap = new HashMap<String, Object>(16);
        rspMap.put("access_token", accessToken);
        rspMap.put("expires_in", EXPIRETIME);
        rspMap.put("isLogin", isLogin(String.valueOf(userId)));
        rspMap.put("deviceTypes", loginUser.getPermissions());
        rspMap.put("staffId", loginUser.getUserid());
        rspMap.put("staffName", loginUser.getSysUser().getNickName());
        rspMap.put("mobile", loginUser.getSysUser().getPhonenumber());
        long tokenTime = getTokenTime();
        //对token进行存储
        redisService.setCacheObject(LOGIN_STAFF_KEY + userId, token, tokenTime, TimeUnit.MINUTES);
        return rspMap;
    }

    public boolean isLogin(String userId) {
        String existingTokenKey = redisService.getCacheObject(LOGIN_USER_KEY + userId);
        return existingTokenKey != null;
    }

    public boolean isKey(String key) {
        return redisService.hasKey(getTokenKey(key));
    }

    /**
     * 删除已有的token
     */
    public void delExistingToken(Long userId) {
        String existingTokenKey = redisService.getCacheObject(LOGIN_USER_KEY + userId);
        if (existingTokenKey != null) {
            redisService.deleteObject(getTokenKey(existingTokenKey));
            redisService.deleteObject(LOGIN_USER_KEY + userId);
        }
    }

    /**
     * 获取用户身份信息
     *
     * @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) {
            log.error("获取用户信息异常'{}'", e.getMessage());
        }
        return user;
    }

    /**
     * 设置用户身份信息
     */
    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) {
        long tokenTime = getTokenTime();
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + tokenTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, tokenTime, TimeUnit.MINUTES);
    }

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

    private Long getTokenTime(){
        long tokenTime = 20L;
        String redisResult = redisService.getCacheObject("sys_config:"+ "sys.visit.tokentime");
        if(StringUtils.isNotEmpty(redisResult)) {
            try {
                tokenTime = Long.parseLong(redisResult);
            } catch (Exception e) {
                tokenTime = 43200L; //MINUTES
            }
        }else {
            Long result = systemConfig.getTokenTime();
            if (!ObjectUtil.isEmpty(result)){
                tokenTime = result;
            }
        }
        return tokenTime;
    }
}
