package com.ai.da.service.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.ai.da.common.RabbitMQ.MQPublisher;
import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.service.RabbitMQService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RabbitMQServiceImpl implements RabbitMQService {

    @Resource
    private MQPublisher mqPublisher;

    @Override
    public void publishMessageToGenerate(String message) {
        mqPublisher.sendGenerateMessage(message);
    }

    @Override
    public void publishMessageToSR(String message) {
        mqPublisher.sendSRMessage(message);
    }
    @Override
    public Integer getMessageCount(String queueUrl) {

        String url = "http://localhost:15672/api/queues/%2f/generate-queue";

        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
                .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒)
                .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒)
                .build();
        Request request = new Request.Builder()
                .url(queueUrl)
                .method("GET",null)
                .addHeader("Authorization", "Basic Z3Vlc3Q6Z3Vlc3Q=")
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException ioException) {
            log.error("RabbitMQService##" + "getMessage异常###{}", ExceptionUtil.getThrowableList(ioException));
        }

        String bodyString;
        // 生成失败
        if (Objects.isNull(response) || Objects.isNull(response.body())) {
            log.error("RabbitMQService##getMessageCount异常###{}", "response or body is empty!");
            throw new BusinessException("compose-layer.interface.exception");
        }else if (response.code() != HttpURLConnection.HTTP_OK){
            log.error("RabbitMQService##getMessageCount异常###{}", "Response error!Response code ## " + response.code() + " ##");
            throw new BusinessException("compose-layer.interface.exception");
        } else {
            try {
                bodyString = response.body().string();
            } catch (IOException e) {
                throw new BusinessException("compose-layer.interface.exception");
            }
        }
        JSONObject jsonObject = JSON.parseObject(bodyString);
        String messageCount = jsonObject.get("messages").toString();
        return Integer.parseInt(messageCount);
    }
}
