package com.ruoyi.interfaces.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.interfaces.domain.PtApp;
import com.ruoyi.interfaces.enums.TokenError;
import com.ruoyi.interfaces.service.InterfaceTokenService;
import com.ruoyi.interfaces.service.PtAppService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author LinQiLong
 * @date 4/1/2022 4:48 PM
 */
@Service
public class InterfaceTokenServiceImpl implements InterfaceTokenService {

    @Autowired
    private PtAppService ptAppService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 令牌自定义标识
     */
    @Value("${token.header}")
    private String header;

    /**
     * 令牌有效期（默认1天）
     */
    @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 static final String CLIENT_CREDENTIAL = "client_credential";

    /**
     * 创建令牌
     *
     * @param ptApp 用户信息
     * @return 令牌
     */
    @Override
    public String createToken(PtApp ptApp) {
        ptApp.setRqTime(new Date());
        ptApp.setExpireTime(ptApp.getRqTime().getTime() + expireTime * MILLIS_MINUTE);
        // 根据 token 将ptApp缓存
        String token = IdUtils.fastUUID();
        redisCache.setCacheObject(token, ptApp, expireTime, TimeUnit.MINUTES);
        return token;
    }

    @Override
    public Map<String, Object> token(String grantType, String appId, String secret) {
        PtApp ptApp = ptAppService.get(appId);
        if (ptApp == null) {
            return failResponse(TokenError.APPID_ERR);
        } else if (!Optional.of(ptApp).map(PtApp::getAppSecret).isPresent() ||
                !ptApp.getAppSecret().equals(secret)) {
            return failResponse(TokenError.APPSECRET_ERR);
        } else if (!CLIENT_CREDENTIAL.equals(grantType)) {
            return failResponse(TokenError.GRANT_TYPE_ERR);
        }

        Map<String, Object> ret = new HashMap<>(2);
        ret.put("access_token", createToken(ptApp));
        ret.put("expires_in", expireTime);
        return ret;
    }

    private Map<String, Object> failResponse(int code, String msg) {
        Map<String, Object> ret = new HashMap<>(2);
        ret.put("errcode", code);
        ret.put("errmsg", msg);
        return ret;
    }

    private Map<String, Object> failResponse(TokenError tokenError) {
        return failResponse(tokenError.getCode(), tokenError.getInfo());
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    @Override
    public String getAppIdFromToken(String token) {
        PtApp ptApp = redisCache.getCacheObject(token);
        return Optional.ofNullable(ptApp).map(PtApp::getAppId).orElse(null);
    }
}
