package com.hfkj.openapi.v1.service.impl;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.GenerateUtil;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.openapi.v1.model.TokenGrantType;
import com.hfkj.openapi.v1.model.TokenModel;
import com.hfkj.openapi.v1.service.AuthTokenService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @className: AuthTokenServiceImpl
 * @author: HuRui
 * @date: 2023/5/23
 **/
@Service("authTokenService")
public class AuthTokenServiceImpl implements AuthTokenService {

    public static String OPEN_API_TOKEN = "_OPEN_API_TOKEN";

    private static Long expiresTime = 7200L;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public TokenModel createToken(String merNo) {
        // 生成64位字符token;
        String token = GenerateUtil.generateRandomString(64);
        redisUtil.set(merNo+OPEN_API_TOKEN, token, 7200);


        return new TokenModel(TokenGrantType.CLIENT_CREDENTIALS, token, expiresTime);
    }

    @Override
    public TokenModel refresh(String merNo) {
        Object token = redisUtil.get(merNo+OPEN_API_TOKEN);
        if (token == null) {
            throw ErrorHelp.genException(SysCode.OpenApi, ErrorCode.OPEN_API_TOKEN_ERR, "");
        }
        redisUtil.set(merNo+OPEN_API_TOKEN, token.toString(), 7200);
        return new TokenModel(TokenGrantType.CLIENT_CREDENTIALS, token.toString(), expiresTime);
    }
}
