package com.ai.da.common.utils;

import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.model.dto.AlipayHKRequestDTO;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.time.Instant;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AlipayHKRequestUtil {

    public String requestAlipayHK(AlipayHKRequestDTO alipayHKRequestDTO) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
                .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒)
                .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒)
                .build();
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        long epochMilli = Instant.now().toEpochMilli();
        log.info("Alipay-HK send request unix timestamp: {}", epochMilli);

        String jsonString = JSONObject.toJSONString(alipayHKRequestDTO, SerializerFeature.WriteMapNullValue);
//        log.info(jsonString);

        RequestBody body = RequestBody.create(mediaType, jsonString);

        Request request = new Request.Builder()
//                .url("https://aqs-api.sandbox-codpayment.com/v1/service")
                .url("https://aqs-api.codpayment.com/v1/service")
                .method("POST", body)
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .build();
        Response response;
        String bodyString;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            bodyString = response.body().string();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.parseObject(bodyString);
        boolean success = (boolean) jsonObject.get("success");
        if (success){
            return bodyString;
        } else {
            String message = jsonObject.get("error_code").toString() + ":" + jsonObject.get("error");
            log.error("Alipay return message : {}", message);
            throw new BusinessException("Alipay return message : " + message);
        }
    }

}
