package com.dxhy.erp.utils;

import com.alibaba.fastjson.JSONObject;
import com.dxhy.erp.entity.kfpt.ApiRequest;
import com.dxhy.erp.entity.kfpt.ApiResponse;
import com.dxhy.erp.entity.kfpt.TokenRequest;
import com.dxhy.erp.entity.kfpt.TokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 接口工具类
 *
 * @author REI
 */
@Component
@Slf4j
public class ApiUtils {

    @Value("${params.api.tokenUrl}")
    private String tokenUrl;
    @Value("${params.api.connTimeout}")
    private int connTimeout;
    @Value("${params.api.readTimeout}")
    private int readTimeout;
    private String contentType = "application/json";
    private String charset = "UTF-8";

    private TokenResponse callToken(String url, TokenRequest tokenRequest) {
        final DateTime start = DateTime.now();
        String body = JSONObject.toJSONString(tokenRequest);
        String result = null;
        try {
            result = HttpClientUtils.post(url, body, contentType, charset, connTimeout, readTimeout);
        } catch (Exception e) {
            log.error("<线程" + Thread.currentThread().getId() + ">调用开放平台获取token异常：", e);
        } finally {
            log.info("<线程{}>interface={}|param={}|result={}|responseTime={}",
                    Thread.currentThread().getId(), url, body, result, new Duration(start, DateTime.now()).getMillis());
        }
        return JSONObject.parseObject(result, TokenResponse.class);
    }


    public ApiResponse callApi(String url, String entCode, Object content, String accessToken, String requestId) {
        final DateTime start = DateTime.now();
        ApiRequest apiRequest = new ApiRequest();
        apiRequest.setContent(Base64.encode(JSONObject.toJSONBytes(content)));
        apiRequest.setEntCode(entCode);
        apiRequest.setDataExchangeId(requestId);
        String body = JSONObject.toJSONString(apiRequest);
        url = url + accessToken;
        String result = null;
        try {
            result = HttpClientUtils.post(url, body, contentType, charset, connTimeout, readTimeout);
        } catch (Exception e) {
            log.error("<线程" + Thread.currentThread().getId() + ">调用开放平台业务接口异常：", e);
        } finally {
            log.info("<线程{}>interface={}|param={}|result={}|responseTime={}",
                    Thread.currentThread().getId(), url, body, result, new Duration(start, DateTime.now()).getMillis());
        }
        ApiResponse apiResponse = JSONObject.parseObject(result, ApiResponse.class);
        return apiResponse;

    }


    public TokenResponse getToken(String appKey, String appSecret) {
        TokenRequest tokenRequest = new TokenRequest();
        tokenRequest.setAppKey(appKey);
        tokenRequest.setAppSecret(appSecret);
        TokenResponse tokenResponse = callToken(tokenUrl, tokenRequest);
        if (tokenResponse != null && StringUtils.isEmpty(tokenResponse.getError())) {
            return tokenResponse;
        } else {
            return null;
        }
    }

}
