package com.tykj.workflowcore.user.service.impl;

import com.tykj.workflowcore.user.dao.StorageKeyDao;
import com.tykj.workflowcore.user.pojo.StorageKey;
import com.tykj.workflowcore.user.pojo.UserDetail;
import com.tykj.workflowcore.user.service.StorageKeyService;
import com.tykj.workflowcore.user.util.CipherUtil;
import com.tykj.workflowcore.user.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class StorageKeyServiceImpl implements StorageKeyService {
    @Autowired
    private StorageKeyDao storageKeyDao;

    @Override
    public StorageKey getKeys() {
        List<StorageKey> storageKeyList = storageKeyDao.findAll();
        if (storageKeyList!=null){
            return storageKeyList.get(0);
        }
        return null;
    }

    @Override
    public String generateUserToken(UserDetail userDetail) {
        List<StorageKey> storageKeyList = storageKeyDao.findAll();
        StorageKey storageKey = storageKeyList.get(0);
        //将用户信息装入map
        Map<String, Object> userInfoMap = userDetail.toMap();
        //将用户信息转为jwt并设置过期时间-->利用签名私钥生成jwt
        String tokenData = JwtUtil.generateToken(userInfoMap, 60 * 60 * 2, CipherUtil.string2PrivateKey(storageKey.getSignPrivateKey()));
        //利用rsa公钥对jwt加密
        String token = CipherUtil.encrypt(tokenData, CipherUtil.string2PublicKey(storageKey.getRsaPublicKey()));
//        //将用户信息转为jwt并设置过期时间-->利用签名私钥生成jwt
//        String token = jwtTokenUtils.createToken(userInfoMap);
        System.out.println("应用token:"+token);
        return token;
    }

    @Override
    public String generateUserToken(Map<String, Object> userInfoMap) {

        List<StorageKey> storageKeyList = storageKeyDao.findAll();
        StorageKey storageKey = storageKeyList.get(0);
        String tokenData = JwtUtil.generateToken(userInfoMap, 60 * 60 * 1000 * 24, CipherUtil.string2PrivateKey(storageKey.getSignPrivateKey()));
        //利用rsa公钥对jwt加密
        String token = CipherUtil.encrypt(tokenData, CipherUtil.string2PublicKey(storageKey.getRsaPublicKey()));
//        //将用户信息转为jwt并设置过期时间-->利用签名私钥生成jwt
//        String token = jwtTokenUtils.createToken(userInfoMap);
        System.out.println("应用token:"+token);
        return token;
    }
}
