package com.xunmei.sync.service.api;

import com.alibaba.fastjson.JSON;
import com.xunmei.common.core.exception.SystemException;
import com.xunmei.common.core.http.service.CustomHttpClient;
import com.xunmei.common.core.http.service.params.HttpParams;
import com.xunmei.common.core.http.service.result.ResultExecute;
import com.xunmei.sync.config.ThirdPartySystemConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Slf4j
@Component
public class FjnxApi implements ResultExecute {
    @Autowired
    private CustomHttpClient httpClient;

    @Autowired
    private ThirdPartySystemConfig thirdPartySystemConfig;

    public <T> T get(final HttpParams httpParams) {
        httpParams.setUrl(this.thirdPartySystemConfig.getFjnxPortalIp() + httpParams.getUrl());
        return this.httpClient.execute(httpParams, this);
    }

    @Override
    public Object toBody(final Response response, final HttpParams request, final StopWatch stopWatch) throws Exception {
        final String body = response.body()
                .string();
        if (response.code() != 200) {
            throw new SystemException("100002", String.format("[ %s ] => [ %s ]", request, body));
        }
        Object result = null;
        if (StringUtils.isBlank(body)) {
            return null;
        }
        if (body.startsWith("[")) {
            result = JSON.parseArray(body);
        } else {
            result = JSON.parseObject(body);
        }
        if (result == null) {
            log.warn("[ {} ]无法获取到数据 => [ {} ]", request, body);
        }
        return result;
    }
}
