package com.gyee.wisdom.alarm.sharding.transport.restful;


import com.gyee.wisdom.alarm.sharding.taos.TsData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class RestfulClient {

    @Value("${adapterUrl}")
    String adapterUrl;

    private RestTemplate restTemplate;

    private String adpUrl;

    private String getAdpUrl() {
        if (adpUrl == null) {
            adpUrl = adapterUrl;
        }

        return adpUrl;
    }

    private String adpHistorySnapUrl;

    private String getAdpHistorySnapUrl() {
        if (adpHistorySnapUrl == null) {
            adpHistorySnapUrl = getAdpUrl() + "/history/snap?";
        }
        return adpHistorySnapUrl;
    }

    private RestTemplate getRestTemplate() {
        if (restTemplate == null) {
            //复杂构造函数的使用
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(10000);// 设置超时
            requestFactory.setReadTimeout(10000);
            restTemplate = new RestTemplate(requestFactory);
        }

        return restTemplate;
    }

    public List<TsData> getHistorySnap(String tagName,String thingId,
                                       String thingType,String uniformCode,
                                       Long startTs,Long endTs,Integer interval) throws Exception {
        StringBuilder urlBuilder=new StringBuilder(getAdpHistorySnapUrl()+"1=1&") ;
       if(StringUtils.isNotBlank(tagName))
            urlBuilder.append("tagName="+tagName+"&");
        if(StringUtils.isNotBlank(thingId))
            urlBuilder.append("thingId="+thingId+"&");
        if(StringUtils.isNotBlank(thingType))
            urlBuilder.append("thingType="+thingType+"&");
        if(StringUtils.isNotBlank(uniformCode))
            urlBuilder.append("uniformCode="+uniformCode+"&");
        if(startTs!=null&&startTs!=0)
            urlBuilder.append("startTs="+startTs+"&");
        if(endTs!=null&&endTs!=0)
            urlBuilder.append("endTs="+endTs+"&");
        if(interval!=null&&interval!=0)
            urlBuilder.append("interval="+interval+"&");

        List<TsData> tsDataList = new ArrayList<>();
        ResponseEntity<Object> resp = getRestTemplate().getForEntity(urlBuilder.toString(), Object.class);
        if (resp.getStatusCode() == HttpStatus.OK) {
            tsDataList= (List<TsData>) resp.getBody();
        } else {
            log.error(resp.getStatusCodeValue() + "");
        }
        return tsDataList;
    }



}
