package com.lightinit.hsdatagateway.modules.foreign.service;

import com.alibaba.fastjson.JSON;
import com.lightinit.hsdatagateway.common.exceptions.HttpTransferErrorException;
import com.lightinit.hsdatagateway.modules.foreign.model.RequestDto;
import com.lightinit.hsdatagateway.modules.foreign.model.ResponseModel;
import com.lightinit.hsdatagateway.modules.foreign.util.HttpUtil;
import com.lightinit.hsdatagateway.modules.foreign.model.RequestDto;
import com.lightinit.hsdatagateway.modules.foreign.model.ResponseModel;
import com.lightinit.hsdatagateway.modules.foreign.util.HttpUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * @Author: yangrui
 * @Date: 2019/3/5 12:29
 */
@Component
public class BusinessExecuteService{
    private RequestDto requestDto;

    private CloseableHttpClient httpClient;

    public BusinessExecuteService(@Qualifier("httpClient") CloseableHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public BusinessExecuteService setRequestDto(RequestDto requestDto) {
        this.requestDto = requestDto;
        return this;
    }

    public RequestDto call(){
        ResponseModel responseModel = null;
        requestDto.setTime(System.currentTimeMillis() - requestDto.getTime());
        switch (requestDto.getMethod()){
            case "GET" :
                responseModel = HttpUtil.httpGet(httpClient, requestDto.getUrl(), requestDto.getParam(), "utf-8");
                break;
            case "POST":
                responseModel = HttpUtil.httpPostForm(httpClient, requestDto, "utf-8");
//                responseModel = HttpUtil.httpPostForm(httpClient,requestDto.getUrl(), requestDto.getBody(), requestDto.getContentType(), "utf-8");
                break;
            case "PUT" :
                responseModel = HttpUtil.httpPut(httpClient, requestDto.getUrl(), requestDto.getBody() ,requestDto.getContentType(), "utf-8");
                break;
            case "DELETE" :
                responseModel = HttpUtil.httpDelete(httpClient, requestDto.getUrl(), requestDto.getParam(), "utf-8");
                break;
            default:
        }

//        if (responseModel.getCode() != 200){
//            throw new HttpTransferErrorException(JSON.toJSONString(responseModel), responseModel.getCode().toString());
//        }
        requestDto.setResponseModel(responseModel);
        return requestDto;
    }
}
