package com.example.myapplication.Tool;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.example.myapplication.DataBase.DatabaseHelper;
import com.example.myapplication.api.CommonService;
import com.example.myapplication.model.ApiResponse;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class DynamicDataFetcher {
    private final String token;
    private final CommonService commonService;
    private final DatabaseHelper dbHelper;
    private final Context context;
    private final String dataType; // 新增：数据类型标识

    /**
     * @param token   用户令牌
     * @param context 上下文
     * @param dataType 数据类型标识（如"work_types"、"image_sources"等）
     */
    public DynamicDataFetcher(String token, Context context, String dataType) {
        this.token = token;
        this.context = context;
        this.dataType = dataType;
        this.dbHelper = new DatabaseHelper(context);
        Retrofit retrofit = RetrofitClient.getClient(token);
        this.commonService = retrofit.create(CommonService.class);
    }

    /**
     * 同步获取动态数据列表
     */
    public List<Map<String, String>> fetchDynamicDataSync() throws IOException {
        if (isNetworkAvailable()) {
            Call<ApiResponse<List<Map<String, String>>>> call = commonService.getDynamicDataList();

            Response<ApiResponse<List<Map<String, String>>>> response = call.execute();

            if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                List<Map<String, String>> result = response.body().getData();
                // 保存到数据库（带数据类型标识）
                dbHelper.saveDynamicData(dataType, result);
                return result;
            } else {
                throw new IOException("请求失败，状态码: " + response.code());
            }
        } else {
            // 无网络时从数据库获取（带数据类型标识）
            return dbHelper.getDynamicData(dataType);
        }
    }

    /**
     * 异步获取动态数据列表
     */
    public void fetchDynamicDataAsync(DynamicDataCallback callback) {
        List<Map<String, String>> cachedData = dbHelper.getDynamicData(dataType);
        if (!cachedData.isEmpty()) {
            callback.onSuccess(cachedData);
        }

        if (isNetworkAvailable()) {
            Call<ApiResponse<List<Map<String, String>>>> call = commonService.getDynamicDataList();

            call.enqueue(new Callback<ApiResponse<List<Map<String, String>>>>() {
                @Override
                public void onResponse(Call<ApiResponse<List<Map<String, String>>>> call,
                                       Response<ApiResponse<List<Map<String, String>>>> response) {
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {

                        List<Map<String, String>> result = response.body().getData();

                        // 保存到数据库（带数据类型标识）
                        dbHelper.saveDynamicData(dataType, result);
                        callback.onSuccess(result);
                    } else if (cachedData.isEmpty()) {
                        callback.onFailure(new IOException("请求失败，状态码: " + response.code()));
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<List<Map<String, String>>>> call, Throwable t) {
                    if (cachedData.isEmpty()) {
                        callback.onFailure(t);
                    }
                }
            });
        } else if (cachedData.isEmpty()) {
            callback.onFailure(new IOException("无网络连接且无缓存数据"));
        }
    }

    /**
     * 检查网络是否可用
     */
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }
        return false;
    }

    /**
     * 获取该数据类型的最后同步时间
     */
    public long getLastSyncTime() {
        return dbHelper.getDynamicDataLastSync(dataType);
    }

    /**
     * 清除当前数据类型的缓存
     */
    public void clearCache() {
        dbHelper.clearDynamicData(dataType);
    }

    public interface DynamicDataCallback {
        void onSuccess(List<Map<String, String>> dataList);
        void onFailure(Throwable t);
    }
}