package com.quyunshuo.module.home.utils;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
 * RxHttpUploader uploader = new RxHttpUploader(
 *     2000,           // 基础间隔2秒
 *     2.0,            // 退避因子2.0
 *     30000,          // 重置间隔30秒
 *     3
 *     new RxUploader.UploadCallback() {
 *         @Override
 *         public void onSuccess() {
 *             runOnUiThread(() ->
 *                 Toast.makeText(context, "上传成功!", Toast.LENGTH_SHORT).show());
 *         }
 *
 *         @Override
 *         public void onFailure(String error) {
 *             runOnUiThread(() ->
 *                 Toast.makeText(context, "上传失败: " + error, Toast.LENGTH_SHORT).show());
 *         }
 *
 *         @Override
 *         public void onRetry(int attempt, long nextRetryDelay) {
 *             Log.d("Upload", "重试 #" + attempt + " 将在 " + nextRetryDelay + "ms后");
 *         }
 *     }
 * );
 *
 * // 执行上传
 * uploader.uploadData(data);
 * */

public class RxHttpUploader extends RxUploader<String> {


    public RxHttpUploader(long baseRetryInterval, double backoffFactor, long resetInterval, int resetAfterAttempts, UploadCallback callback) {
        super(baseRetryInterval, backoffFactor, resetInterval, resetAfterAttempts, callback);
    }

    @Override
    protected boolean doUpload(String data) throws Exception {
        OkHttpClient client = new OkHttpClient();

        // 构建JSON请求体
        String json = data;
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, mediaType);

        // 创建请求
        Request request = new Request.Builder()
                .url("https://api.example.com/upload")
                .post(body)
                .build();

        // 执行请求
        try (Response response = client.newCall(request).execute()) {
            return response.isSuccessful();
        }


    }
}
