package com.seeyon.utils.http;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.aicloud.common.JsonUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class OaRestClient {

    private static final Logger log = LoggerFactory.getLogger(OaRestClient.class);
    private String oaHost;
    private String restName;
    private String restPwd;
    private Boolean cacheToken = false;
    private ConcurrentHashMap<String, String> tokenCache = new ConcurrentHashMap<>();

    public OaRestClient(String oaHost, String restName, String restPwd, Boolean cacheToken) {
            this.oaHost = oaHost;
            this.restName = restName;
            this.restPwd = restPwd;
            this.cacheToken = cacheToken;
    }

    public OaResp sendGet(String bizName, String url) throws Exception {
        Map<String,String> headers = new HashMap<>();
        headers.put("token",getToken());
        log.info(bizName + "请求链接为：" + url);
        String respStr = HttpClient.httpGet(oaHost + "/seeyon/rest" + url,headers,null);
        log.info(bizName + "响应结果为：" + respStr);
        return resovleResp(respStr);
    }

    public OaResp sendPost(String bizName,String url,Map<String,Object> params,String token) throws Exception {
        Map<String,String> headers = new HashMap<>();
        headers.put("token",token);
        String paramStr = JsonUtils.toJSONString(params);
        log.info(bizName + "请求参数为：" + paramStr);
        String respStr = HttpClient.httpPostRaw(oaHost + "/seeyon/rest" + url,paramStr,headers,null);
        log.info(bizName + "响应结果为：" + respStr);
        return resovleResp(respStr);
    }


    public OaResp sendPost(String bizName,String url,Map<String,Object> params) throws Exception {
//        Map<String,String> headers = new HashMap<>();
//        headers.put("token",getToken());
//        String paramStr = JsonUtils.toJSONString(params);
//        log.info(bizName + "请求参数为：" + paramStr);
//        String respStr = HttpClient.httpPostRaw(oaHost + "/seeyon/rest" + url,paramStr,headers,null);
//        log.info(bizName + "响应结果为：" + respStr);
//        return resovleResp(respStr);
        return sendPost(bizName,url,params,getToken());
    }

    OaResp resovleResp(String respStr){
        return JsonUtils.parseObject(respStr,OaResp.class);
    }

    private String applyToken() {
        String url = oaHost +"/seeyon/rest/token/" + restName + "/" + restPwd + "?loginName=" + restName;
        DefaultHttpClient client = new DefaultHttpClient();
        String result = "";
        HttpGet get = new HttpGet(url);
        // 添加 Headers 信息
        get.addHeader(new BasicHeader("Accept", "application/json"));
        try {
            HttpResponse res = client.execute(get);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(res.getEntity());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String token = null;
        if(result.contains("{")) {
            JSONObject jsObj = JSONObject.parseObject(result);
            token = jsObj.get("id").toString();
        }else {
            token = result;
        }
        return token;
    }

    private String getToken(){
        if(cacheToken) {
            String token = tokenCache.get(restName);
            if(token != null && !checkExpire(token)) {
                return token;
            }else {
                String tokenStr = applyToken();
                tokenCache.put(restName, tokenStr);
                return tokenStr;
            }
        }
        return applyToken();
    }

    private boolean checkExpire(String token) {
        String url = oaHost + "/seeyon/rest/cap4/batch/refresh";
        try{
            Map<String,String> headers = new HashMap<>();
            headers.put("token",token);
            headers.put("loginName",restName);
            String respStr = HttpClient.httpPostRaw(url, null, headers,null);
            Map map = JsonUtils.parseObject(respStr, Map.class);
            if("0".equals(map.get("code"))) {
                return false;
            }else {
                return true;
            }
        } catch (Exception e){
            return true;
        }
    }

}