package com.lantone.qc.security.facade;

import com.lantone.qc.pub.model.vo.LoginKeyVO;
import com.lantone.qc.pub.util.StringUtil;
import com.lantone.qc.security.exception.CommonErrorCode;
import com.lantone.qc.security.exception.CommonException;
import com.lantone.qc.security.util.RSAEncrypt;
import com.lantone.qc.security.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class TokenFacade {

    /**
     * 获取token
     *
     * @param loginKeyVO
     * @return 返回token信息
     */
    public String getToken(LoginKeyVO loginKeyVO) {
        Map<String, String> tokenMap = TokenUtil.tokenMap;
        // 记录信息
        log.info(tokenMap.get("server.provider") + "——" + tokenMap.get("server.hospital") + "登录了！");

        if (StringUtil.isEmpty(loginKeyVO.getLoginKey())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "loginKey为空");
        }
        try {
            // 获取文件中的loginKey，已解密
            String loginKey = tokenMap.get("server.key");
            if (!loginKey.equals(loginKeyVO.getLoginKey())) {
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "loginKey不匹配");
            }
            // 生成token，格式如下：server.remainday=xx$$server.validtime=xx
            StringBuffer sb = new StringBuffer();
            sb.append("server.remainday=" + tokenMap.get("server.remainday"));
            sb.append("$$");
            // 分钟数 * 60 * 1000，转换成毫秒
            Long date = new Date().getTime() + Integer.parseInt(tokenMap.get("server.validtime")) * 60 * 1000;
            sb.append("server.validtime=" + date);
            return RSAEncrypt.encrypt(sb.toString());
        } catch (Exception e) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "获取token失败");
        }
    }

}
