package thyyxxk.webserver.service.jcptmobile;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.dtflys.forest.Forest;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.utils.ForestDataType;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.envionment.JcptMobile;
import thyyxxk.webserver.utils.TokenUtil;


@Service
public class JcptMobileService {
    private final RSA rsa;
    private final JcptMobile jcptMobile;

    public JcptMobileService(JcptMobile jcptMobile) {
        this.jcptMobile = jcptMobile;
        rsa = new RSA(null, jcptMobile.getPublicKey());
    }

    public ForestRequest<?> request(String url, String request) {
        ForestRequest<?> forestRequest;
        if ("get".equals(request)) {
            forestRequest = Forest.get(url);
        } else {
            forestRequest = Forest.post(url);
        }

        String token = TokenUtil.getInstance().getTokenUserId() + "_" + DateUtil.now();
        String encrypted = rsa.encryptBase64(token, KeyType.PublicKey);

        forestRequest.addHeader("token", encrypted)
                .bodyType(ForestDataType.JSON)
                .addHeader("content-type", "application/json")
                .basePath(jcptMobile.getAddress() + "/thyy/moveEmr/api");
        return forestRequest;
    }

    public ForestRequest<?> get(String url) {
        return request(url, "get");
    }

    public ForestRequest<?> post(String url) {
        return request(url, "post");
    }

}
