package com.friday.custody.service.trustService.htsc.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class HTSCRemoteUtil {

    public static HashMap getDataFromRemote(String url, HttpHeaders headers) {
        HashMap remoteMap = new HashMap();
        try {
            remoteMap = JSON.parseObject(JSON.toJSONString(RestTemplateUtil.getDataFromRemote(url,
                    headers).getBody()),
                    HashMap.class);
        }catch (Exception e){
            log.error("调用上游失败url= {} : {}", url, e);
            remoteMap.put("code", 101);
            remoteMap.put("errorMsg", e.getMessage());

        }
        return remoteMap;
    }

    public static HashMap getDataFromRemote(String url, HttpHeaders headers, ReentrantLock lock, long sleepTime, int waitTime) {
        HashMap remoteResp =  new HashMap();
        try {
            ReentrantLockUtil.lock(lock, waitTime);
            remoteResp = getDataFromRemote(url, headers);
        } catch (Exception e) {
            log.error("url:{},exception:{}", url, e.getMessage());
            remoteResp.put("code", 101);
            remoteResp.put("errorMsg", e.getMessage());
        } finally {
            try {
                Thread.sleep(sleepTime);
            } catch (Exception e) {
                Thread.currentThread().interrupt();
                log.error("getDataFromRemote url:{},exception:{}",url,e.getMessage());
            }
            if (lock.isLocked()){
                lock.unlock();
            }
        }
        return remoteResp;
    }
}
