package com.example.myapplication.Tool;

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

import com.example.myapplication.DataBase.DatabaseHelper;
import com.example.myapplication.api.PartService;
import com.example.myapplication.model.ApiResponse;
import com.example.myapplication.model.PartResponse;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PartListFetcher {
    private final Context context;
    private final String token;
    private final String projectId;

    private final PartService partService;
    private final DatabaseHelper dbHelper;

    public PartListFetcher(Context context, String token, String projectId) {
        this.context = context;
        this.token = token;
        this.projectId = projectId;

        this.dbHelper = new DatabaseHelper(context);

        // 初始化Retrofit
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = RetrofitClient.getClient(token);

        this.partService = retrofit.create(PartService.class);
    }

    /**
     * 同步获取部件列表
     * @return 部件列表
     * @throws IOException 网络异常
     * @throws ApiException API异常
     */
    public List<PartResponse> fetchPartListSync() throws IOException, ApiException {
        if (isNetworkAvailable()) {
            // 有网络时从服务器获取并更新数据库
            List<PartResponse> serverParts = fetchFromServer();
            dbHelper.saveParts(serverParts);
            return serverParts;
        } else {
            // 无网络时从数据库获取
            return dbHelper.getAllParts();
        }
    }


    /**
     * 异步获取部件列表
     * @param callback 回调接口
     */
    public void fetchPartListAsync(final PartListCallback callback) {
        // 先从数据库获取数据快速显示
        List<PartResponse> cachedParts = dbHelper.getAllParts();
        if (!cachedParts.isEmpty()) {
            callback.onSuccess(cachedParts);
        }

        // 检查网络连接
        if (isNetworkAvailable()) {
            // 有网络时从服务器获取并更新数据库
            fetchFromServerAsync(new PartListCallback() {
                @Override
                public void onSuccess(List<PartResponse> partList) {
                    dbHelper.saveParts(partList);
                    callback.onSuccess(partList);
                }

                @Override
                public void onFailure(Throwable t) {
                    // 服务器获取失败，如果之前有缓存数据则不报错
                    if (cachedParts.isEmpty()) {
                        callback.onFailure(t);
                    }
                }
            });
        } else if (cachedParts.isEmpty()) {
            // 无网络且无缓存数据
            callback.onFailure(new IOException("无网络连接且无缓存数据"));
        }
    }
    public String getPartIdByName(String partName) {
        // 先从数据库查询
        String partId = dbHelper.getPartIdByName(partName);
        if (partId != null) {
            return partId;
        }

        // 数据库中没有则尝试从服务器获取
        if (isNetworkAvailable()) {
            try {
                List<PartResponse> parts = fetchFromServer();
                dbHelper.saveParts(parts);
                // 再次从数据库查询
                return dbHelper.getPartIdByName(partName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
    private List<PartResponse> fetchFromServer() throws IOException, ApiException {
        Call<ApiResponse<List<PartResponse>>> call = partService.getPartList(
                projectId, null,
                null, null, null, null

        );

        Response<ApiResponse<List<PartResponse>>> response = call.execute();

        if (response.isSuccessful() && response.body() != null) {
            ApiResponse<List<PartResponse>> apiResponse = response.body();
            if (apiResponse.isSuccess()) {
                return apiResponse.getData();
            } else {
                throw new ApiException(apiResponse.getCode(), apiResponse.getMsg());
            }
        } else {
            throw new IOException("请求失败，状态码: " + response.code());
        }
    }
    private void fetchFromServerAsync(final PartListCallback callback) {
        Call<ApiResponse<List<PartResponse>>> call = partService.getPartList(
                projectId, null,

                null, null, null, null

        );

        call.enqueue(new retrofit2.Callback<ApiResponse<List<PartResponse>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<PartResponse>>> call,
                                   Response<ApiResponse<List<PartResponse>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<List<PartResponse>> apiResponse = response.body();
                    if (apiResponse.isSuccess()) {
                        callback.onSuccess(apiResponse.getData());
                    } else {
                        callback.onFailure(new ApiException(apiResponse.getCode(), apiResponse.getMsg()));
                    }
                } else {
                    callback.onFailure(new IOException("请求失败，状态码: " + response.code()));
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<PartResponse>>> call, Throwable t) {
                callback.onFailure(t);
            }
        });
    }

    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;
    }
    /**
     * 带筛选条件的异步获取部件列表
     * @param keyword 关键字
     * @param manufacturer 厂商
     * @param model 型号
     * @param type 类型
     * @param callback 回调接口
     */
    public void fetchPartListWithFilterAsync(String keyword, String manufacturer,
                                             String model, String type,
                                             PartListCallback callback) {
        Call<ApiResponse<List<PartResponse>>> call = partService.getPartList(
                projectId,
                null,
                keyword,
                manufacturer,
                model,
                type
        );

        call.enqueue(new retrofit2.Callback<ApiResponse<List<PartResponse>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<PartResponse>>> call,
                                   Response<ApiResponse<List<PartResponse>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<List<PartResponse>> apiResponse = response.body();
                    if (apiResponse.isSuccess()) {
                        callback.onSuccess(apiResponse.getData());
                    } else {
                        callback.onFailure(new ApiException(apiResponse.getCode(), apiResponse.getMsg()));
                    }
                } else {
                    callback.onFailure(new IOException("请求失败，状态码: " + response.code()));
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<PartResponse>>> call, Throwable t) {
                callback.onFailure(t);
            }
        });
    }

    public interface PartListCallback {
        void onSuccess(List<PartResponse> partList);
        void onFailure(Throwable t);
    }
    public String getPartIdByNameSync(String partName) throws IOException, ApiException {
        List<PartResponse> partList = fetchPartListSync();
        for (PartResponse part : partList) {
            if (partName.equals(part.getPartName())) {
                return part.getPartId();
            }
        }
        return null;
    }

    /**
     * 异步根据部件名称获取部件ID
     * @param partName 要查找的部件名称
     * @param callback 回调接口
     */
    public void getPartIdByNameAsync(String partName, PartIdCallback callback) {
        fetchPartListAsync(new PartListCallback() {
            @Override
            public void onSuccess(List<PartResponse> partList) {
                for (PartResponse part : partList) {
                    if (partName.equals(part.getPartName())) {
                        callback.onSuccess(part.getPartId());
                        return;
                    }
                }
                callback.onSuccess(null);
            }

            @Override
            public void onFailure(Throwable t) {
                callback.onFailure(t);
            }
        });
    }

    public interface PartIdCallback {
        void onSuccess(String partId);
        void onFailure(Throwable t);
    }
    public static class ApiException extends Exception {
        private final int code;

        public ApiException(int code, String message) {
            super(message);
            this.code = code;
        }

        public int getCode() {
            return code;
        }

    }
}