package net.northking.cctp.device.util;

import com.hzbank.testteam.autotest.dependencies.authDependency.utils.RequestUtil;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.device.constants.DeviceError;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;


@Component
public class OkHttpClientUtil {


    private final static Logger logger = LoggerFactory.getLogger(OkHttpClientUtil.class);

    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .build();

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    @Async
    public void httpGet(String url) {
        Request request = new Request.Builder().url("http://"+url).get().build();
        httpCall(request);
    }

    @Autowired
    private RestTemplate restTemplate;

    @Async
    public void httpPost(String url,String body,String userId){
        logger.info("userId:"+NKSecurityContext.getUserId());
        logger.info("url:{}",url);
        logger.info("token:"+ RequestUtil.getToken());
        RequestBody requestBody = RequestBody.create(JSON,body);
        //
        Request request = new Request.Builder().url("http://" + url).post(requestBody)
                .addHeader("Authorization", "Bearer " + RequestUtil.getToken()).build();
        httpCall(request);
    }

    public void httpCall(Request request){
        Call call = okHttpClient.newCall(request);
        //异步发送请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.info("OkHttpClient请求失败:", e);
                throw new PlatformRuntimeException(DeviceError.HTTP_CLIENT_ERR);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                responseCode(request,response);
            }
        });
    }


    public void responseCode(Request request,Response response){
        switch(response.code()){
            case 200:
                logger.info("Response Code: 200");
                logger.info("OkHttpClient请求成功:", response.body().toString());
                break;
            case 400:
                logger.info("Response Code: 400");
                throw new PlatformRuntimeException(DeviceError.HTTP_REQUEST_ERR);
            default:
                try {
                    logger.info("Response Code: {}, msg: {}",response.code(), new String(response.body().bytes(), StandardCharsets.UTF_8));
                    Thread.sleep(60000);
                    logger.info("等待一分钟，重新发送http请求");
                    httpCall(request);
                } catch (Exception exception) {
                    logger.info("OkHttpClient请求失败:", exception);
                }
                break;
        }
    }
}
