package com.fujica.abk.slice;

import com.fujica.abk.ResourceTable;
import com.fujica.abk.api.cache;
import com.fujica.abk.utils.Log;
import com.fujica.abk.utils.Toast;
import com.fujica.abk.utils.api;
import com.huawei.hms.accountsdk.constant.CommonConstant;
import com.huawei.hms.accountsdk.exception.ApiException;
import com.huawei.hms.accountsdk.support.account.AccountAuthManager;
import com.huawei.hms.accountsdk.support.account.request.AccountAuthParams;
import com.huawei.hms.accountsdk.support.account.request.AccountAuthParamsHelper;
import com.huawei.hms.accountsdk.support.account.result.AuthAccount;
import com.huawei.hms.accountsdk.support.account.service.AccountAuthService;
import com.huawei.hms.accountsdk.support.account.tasks.OnFailureListener;
import com.huawei.hms.accountsdk.support.account.tasks.OnSuccessListener;
import com.huawei.hms.accountsdk.support.account.tasks.Task;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.IDataAbilityObserver;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.colors.RgbColor;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.location.Location;
import ohos.location.Locator;
import ohos.location.LocatorCallback;
import ohos.location.RequestParam;
import ohos.rpc.RemoteException;
import ohos.sysappcomponents.settings.SystemSettings;
import ohos.utils.zson.ZSONObject;
import com.fujica.abk.model.response.ParkNearRes;
import com.fujica.abk.model.response.Page;
import com.fujica.abk.utils.R;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class MainAbilitySlice extends AbilitySlice {
    // PageSlider相关
    private PageSlider pageSlider;
    private PageSliderProvider pageSliderProvider;

    // 底部导航栏组件
    private DirectionalLayout navMy;
    private DirectionalLayout navFindParking;
    private DirectionalLayout navReserveParking;
    private DirectionalLayout navCurrentLocation;

    // 底部导航栏文字和图标
    private Text textMy;
    private Text textPark;
    private Text textFee;
    private Image iconPark;
    private Image iconPark1;
    private Image iconMy;
    private Image iconMy1;
    private Image iconFee;
    private Image iconFee1;

    // 当前选中的 tab
    private int currentTab = 1; // 0: 我的, 1: 找车位, 2: 预约停车

    // 定位相关
    private Locator locator;
    private LocatorCallback locatorCallback;
    private Location currentLocation; // 当前定位坐标

    // 找车位页面相关
    private Component findParkingPage; // 找车位页面组件
    private Text tabAll; // 全部车场标签
    private Text tabRecommended; // 推荐车场标签
    private Component tabAllUnderline; // 全部车场下划线
    private Component tabRecommendedUnderline; // 推荐车场下划线
    private Button btnDistanceSort; // 距离最近按钮
    private ScrollView parkingListScroll; // 停车场列表滚动视图
    private DirectionalLayout parkingListContainer; // 停车场列表容器
    private int currentPage = 1; // 当前页码
    private int pageSize = 10; // 每页数量
    private boolean isLoading = false; // 是否正在加载
    private boolean hasMore = true; // 是否还有更多数据
    private int filterType = 2; // 筛选类型：2=全部，1=推荐
    private List<ParkNearRes> parkingList = new ArrayList<>(); // 停车场列表数据
    private long lastLoadTime = 0; // 上次加载时间，用于防抖
    private static final long LOAD_THROTTLE_MS = 500; // 防抖时间间隔（毫秒）

    DataAbilityHelper dataAbilityHelper;
    IDataAbilityObserver dataAbilityObserver;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        try {
            //com.fujica.abk_BD8VI9k5bO0HeGAPnhTGeYX++mgKw87G8y+3RZ6nrb9evCePddojupXJN03auUKxTKn1qbFrYQAjFyGumpjsHzw=
            String appId = getApplicationContext().getBundleManager().getBundleInfo(getBundleName(), 0).getAppId();
            Log.info(appId);
        } catch (RemoteException e) {
        }
        cache.setToken(getContext(), "sdfdsfdsf11111111111");
        String token = cache.getToken(getContext());

//        api.http(getContext(), "http://www.baidu.com", "GET", null, null, null);

        // 设置全屏显示
        setFullScreen();

        // 设置布局
        super.setUIContent(ResourceTable.Layout_ability_main);

        // 初始化组件
        initComponents();

        // 设置事件监听
        setupListeners();

        // 初始化定位
        initLocation();

        Button mBtnHuaweiIdSignIn = findComponentById(ResourceTable.Id_btn_hwid_sign_in);
        mBtnHuaweiIdSignIn.setClickedListener((Component c) -> {
            huaweiIdSignIn();
        });

        final String key = "car_license_plate_number";
//        final String key = SystemSettings.Date.TIME_FORMAT;

        dataAbilityHelper = DataAbilityHelper.creator(this);
        dataAbilityObserver = () -> {
            String timeFormat = SystemSettings.getValue(dataAbilityHelper, key);
            setTimeFormat(timeFormat);
        };
        dataAbilityHelper.registerObserver(SystemSettings.getUri(key), dataAbilityObserver);
        String timeFormat1 = SystemSettings.getValue(dataAbilityHelper, "car_license_plate_number");
        String timeFormat = SystemSettings.getValue(dataAbilityHelper, key);
    }

    void setTimeFormat(String timeFormat) {
        String timeStr = "12";
        if (timeStr.equals(timeFormat)) {
            // Display in 12-hour format
        } else {
            // Display in 24-hour format
        }
    }

    void huaweiIdSignIn() {
        AccountAuthService accountAuthService;
        // 1、配置登录请求参数AccountAuthParams，包括请求用户id(openid、unionid)、email、profile（昵称、头像）等。
        // 2、DEFAULT_AUTH_REQUEST_PARAM默认包含了id和profile（昵称、头像）的请求。
        // 3、如需要再获取用户邮箱，需要setEmail();
        // 4、如需要获取其他受限信息，如国家和地区，则需要先申请scope，再设置请求参数。
        AccountAuthParams accountAuthParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
                .setEmail()
                .createParams();
        try {
            accountAuthService = AccountAuthManager.getService(accountAuthParams);
        } catch (ApiException e) {
            // 处理初始化登录授权服务失败，status code标识了失败的原因，请参考API中的错误码参考了解详细错误原因
            e.getStatusCode();
            Toast.error(getContext(),"Init Huawei accountAuthService FAILED.");
            return;
        }
        Toast.info(getContext(),"Init Huawei accountAuthService SUCCESS");

        if (accountAuthService == null) {
            Toast.error(getContext(),"获取不到账号信息");
            return;
        }
        // 调用静默登录接口。
        // 如果华为系统帐号已经登录，并且已经授权，会登录成功；
        // 否则静默登录失败，需要在失败监听中，显式地调用前台登录授权接口，完成登录授权。
        Task<AuthAccount> taskSilentSignIn = accountAuthService.silentSignIn();
//        Task<AuthAccount> taskSilentSignIn = accountAuthService.silentSignIn();
        Toast.info(getContext(),"SilentSign START.");
        // 添加静默登录成功处理监听
        taskSilentSignIn.addOnSuccessListener(authAccount -> updateUI(authAccount));
        // 添加静默登录失败监听
        taskSilentSignIn.addOnFailureListener(e -> {
            if (e instanceof ApiException) {
                ApiException apiException = (ApiException) e;
                Toast.error(getContext(),"SilentSignIn FAILED, status code: " + apiException.getStatusCode() + ". Need to foreground sign in" + "\r\n" + apiException.getStatusMessage()
                        + "\r\n" + apiException.getMessage() + "\r\n" + apiException.getCause());

                // 静默登录失败，显式地调用前台登录授权接口，完成登录授权。
                Task<AuthAccount> taskSignIn = accountAuthService.signIn();
                Toast.info(getContext(),"SignIn foreground START.");
                if (taskSignIn == null) {
                    Toast.info(getContext(),"SignIn foreground task is null.");
                    return;
                }
                taskSignIn.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
                    @Override
                    public void onSuccess(AuthAccount result) {
                        Toast.info(getContext(),"SignIn foreground SUCCESS.");
                        updateUI(result);
                    }
                });
                taskSignIn.addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.info(getContext(),"SignIn foreground FAILED.");
                        if (e instanceof ApiException) {
                            ApiException apiException = (ApiException) e;
                            // 登录失败，status code标识了失败的原因，请参考API中的错误码参考了解详细错误原因
                            apiException.getStatusCode();
                            Toast.info(getContext(),"SignIn foreground FAILED. status code: "
                                    + apiException.getStatusCode()
                                    + ".");
                            if (CommonConstant.RETCODE.SIGN_IN_CANCELLED == apiException.getStatusCode()) {
                                Toast.info(getContext(),"Error message: User click CANCEL or Return, user cancel login in.");
                            }
                        }
                    }
                });
            }
        });
    }

    private void updateUI(AuthAccount authAccount) {
        Toast.info(getContext(),authAccount.getOpenId() + " : " + authAccount.getUnionId());
    }


    /**
     * 设置全屏显示
     */
    private void setFullScreen() {
        try {
            Window window = getWindow();
            if (window != null) {
                WindowManager.LayoutConfig layoutConfig = window.getLayoutConfig().orElse(null);
                if (layoutConfig == null) {
                    layoutConfig = new WindowManager.LayoutConfig();
                }
                layoutConfig.type = WindowManager.LayoutConfig.MARK_FULL_SCREEN;
                window.setLayoutConfig(layoutConfig);
            }
        } catch (Exception e) {
            Log.error("设置全屏失败: " + e.getMessage());
        }
    }

    /**
     * 初始化组件
     */
    private void initComponents() {
        // 初始化PageSlider
        pageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider);
        if (pageSlider != null) {
            // 创建PageSliderProvider
            pageSliderProvider = new PageSliderProvider() {
                private List<Component> pages = new ArrayList<>();

                @Override
                public int getCount() {
                    return 3; // 三个页面：我的、找车位、预约停车
                }

                @Override
                public Object createPageInContainer(ComponentContainer componentContainer, int position) {
                    Component page = null;
                    try {
                        switch (position) {
                            case 0: // 我的
                                page = LayoutScatter.getInstance(MainAbilitySlice.this)
                                        .parse(ResourceTable.Layout_layout_my, null, false);
                                break;
                            case 1: // 找车位
                                page = LayoutScatter.getInstance(MainAbilitySlice.this)
                                        .parse(ResourceTable.Layout_layout_find_parking, null, false);
                                findParkingPage = page;
                                // 初始化找车位页面组件（延迟执行，确保页面已添加到容器）
                                getUITaskDispatcher().asyncDispatch(() -> {
                                    try {
                                        Thread.sleep(100); // 等待页面渲染
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    initFindParkingPage();
                                    // 默认加载数据
                                    loadParkingData(true);
                                });
                                break;
                            case 2: // 预约停车
                                page = LayoutScatter.getInstance(MainAbilitySlice.this)
                                        .parse(ResourceTable.Layout_layout_reserve_parking, null, false);
                                break;
                        }
                        if (page != null) {
                            componentContainer.addComponent(page);
                            pages.add(page);
                        }
                    } catch (Exception e) {
                        Log.error("创建页面失败: " + e.getMessage());
                        e.printStackTrace();
                    }
                    return page;
                }

                @Override
                public void destroyPageFromContainer(ComponentContainer componentContainer, int position, Object object) {
                    if (object instanceof Component) {
                        componentContainer.removeComponent((Component) object);
                        pages.remove(object);
                    }
                }

                @Override
                public boolean isPageMatchToObject(Component component, Object object) {
                    return component == object;
                }
            };

            pageSlider.setProvider(pageSliderProvider);
            // 默认显示找车位页面（索引1）
            pageSlider.setCurrentPage(1);

            // 添加页面切换监听
            pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
                @Override
                public void onPageChosen(int index) {
                    // 页面切换完成
                    currentTab = index;
                    updateBottomNavState(index);
                    Log.info("切换到页面: " + index);
                    // 如果切换到找车位页面，加载数据
                    if (index == 1 && findParkingPage != null) {
                        loadParkingData(true);
                    }
                }

                @Override
                public void onPageSliding(int state, float v, int index) {

                }

                @Override
                public void onPageSlideStateChanged(int state) {
                    // 滑动状态变化
                }
            });
        }

        // 初始化底部导航栏
        initBottomNavigation();
    }

    /**
     * 初始化底部导航栏
     */
    private void initBottomNavigation() {
        navMy = findComponentById(ResourceTable.Id_nav_my);
        navFindParking = findComponentById(ResourceTable.Id_nav_find_parking);
        navReserveParking = findComponentById(ResourceTable.Id_nav_reserve_parking);
        navCurrentLocation = findComponentById(ResourceTable.Id_nav_current_location);

        textMy = findComponentById(ResourceTable.Id_text_my);
        textPark = findComponentById(ResourceTable.Id_text_park);
        textFee = findComponentById(ResourceTable.Id_text_fee);
        iconPark = findComponentById(ResourceTable.Id_icon_park);
        iconPark1 = findComponentById(ResourceTable.Id_icon_park_1);
        iconMy = findComponentById(ResourceTable.Id_icon_my);
        iconMy1 = findComponentById(ResourceTable.Id_icon_my_1);
        iconFee = findComponentById(ResourceTable.Id_icon_fee);
        iconFee1 = findComponentById(ResourceTable.Id_icon_fee_1);

        // 设置点击事件
        if (navMy != null) {
            navMy.setClickedListener(component -> switchToPage(0));
        }
        if (navFindParking != null) {
            navFindParking.setClickedListener(component -> switchToPage(1));
        }
        if (navReserveParking != null) {
            navReserveParking.setClickedListener(component -> switchToPage(2));
        }
        if (navCurrentLocation != null) {
            navCurrentLocation.setClickedListener(component -> {
                Log.info("点击了当前位置按钮");
                locateCurrentPosition();
            });
        }

        // 默认选中找车位
        updateBottomNavState(1);
    }

    /**
     * 切换到指定页面
     */
    private void switchToPage(int index) {
        if (pageSlider != null && index >= 0 && index < 3) {
            pageSlider.setCurrentPage(index);
        }
    }

    /**
     * 更新底部导航栏状态
     */
    private void updateBottomNavState(int index) {
        // 重置所有导航项样式
        Color grayColor = new Color(Color.getIntColor("#FF666666"));
        Color blueColor = new Color(Color.getIntColor("#FA6332"));

        if (textMy != null) {
            textMy.setTextColor(grayColor);
        }
        if (textPark != null) {
            textPark.setTextColor(grayColor);
        }
        if (textFee != null) {
            textFee.setTextColor(grayColor);
        }

        // 设置选中状态
        switch (index) {
            case 0: // 我的
                textMy.setTextColor(blueColor);

                iconMy.setVisibility(Component.HIDE);
                iconMy1.setVisibility(Component.VISIBLE);
                iconFee.setVisibility(Component.VISIBLE);
                iconFee1.setVisibility(Component.HIDE);
                iconPark.setVisibility(Component.VISIBLE);
                iconPark1.setVisibility(Component.HIDE);
                break;
            case 1: // 找车位
                textPark.setTextColor(blueColor);

                iconMy.setVisibility(Component.VISIBLE);
                iconMy1.setVisibility(Component.HIDE);
                iconFee.setVisibility(Component.VISIBLE);
                iconFee1.setVisibility(Component.HIDE);
                iconPark.setVisibility(Component.HIDE);
                iconPark1.setVisibility(Component.VISIBLE);
                break;
            case 2: // 预约停车
                textFee.setTextColor(blueColor);

                iconMy.setVisibility(Component.VISIBLE);
                iconMy1.setVisibility(Component.HIDE);
                iconFee.setVisibility(Component.HIDE);
                iconFee1.setVisibility(Component.VISIBLE);
                iconPark.setVisibility(Component.VISIBLE);
                iconPark1.setVisibility(Component.HIDE);
                break;
        }
    }

    /**
     * 设置事件监听
     */
    private void setupListeners() {
        // 事件监听已在initBottomNavigation中设置
    }

    /**
     * 初始化定位服务
     */
    private void initLocation() {
        try {
            locator = new Locator(this);
            locatorCallback = new LocatorCallback() {
                @Override
                public void onLocationReport(Location location) {
                    // 保存当前位置坐标
                    currentLocation = location;
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();

                    Log.info("定位成功: " + latitude + ", " + longitude);
                    // 定位成功后，如果当前在找车位页面，重新加载数据
                    if (currentTab == 1 && findParkingPage != null) {
                        loadParkingData(true);
                    }
                }

                @Override
                public void onStatusChanged(int type) {
                    Log.info("定位状态变化: " + type);
                }

                @Override
                public void onErrorReport(int errorCode) {
                    Log.error("定位错误: " + errorCode);
                    new ToastDialog(getContext())
                            .setText("定位失败，错误码: " + errorCode)
                            .show();
                }
            };
        } catch (Exception e) {
            Log.error("初始化定位服务失败: " + e.getMessage());
        }
    }

    /**
     * 定位到当前位置
     */
    private void locateCurrentPosition() {
        if (locator == null || locatorCallback == null) {
            Log.error("定位服务未初始化");
            return;
        }

        try {
            // 请求定位
            RequestParam requestParam = new RequestParam(RequestParam.PRIORITY_ACCURACY, 0, 0);
            locator.startLocating(requestParam, locatorCallback);
            Log.info("开始定位...");
        } catch (Exception e) {
            Log.error("定位失败: " + e.getMessage());
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        // 停止定位
        if (locator != null && locatorCallback != null) {
            try {
                locator.stopLocating(locatorCallback);
            } catch (Exception e) {
                Log.error("停止定位失败: " + e.getMessage());
            }
        }

        if (dataAbilityHelper != null) {

        }
        dataAbilityHelper.unregisterObserver(SystemSettings.getUri(SystemSettings.Date.TIME_FORMAT), dataAbilityObserver);
    }

    /**
     * 初始化找车位页面组件
     */
    private void initFindParkingPage() {
        if (findParkingPage == null) {
            return;
        }

        // 获取组件
        btnDistanceSort = (Button) findParkingPage.findComponentById(ResourceTable.Id_btn_distance_sort);
        parkingListScroll = (ScrollView) findParkingPage.findComponentById(ResourceTable.Id_parking_list_scroll);
        parkingListContainer = (DirectionalLayout) findParkingPage.findComponentById(ResourceTable.Id_parking_list_container);

        // 设置标签页点击事件
        if (tabAll != null) {
            tabAll.setClickedListener(component -> switchTab(2)); // 2=全部
        }
        if (tabRecommended != null) {
            tabRecommended.setClickedListener(component -> switchTab(1)); // 1=推荐
        }

        // 设置下拉框点击事件（这里用按钮模拟下拉框）
        if (btnDistanceSort != null) {
            btnDistanceSort.setClickedListener(component -> {
                // 可以在这里显示下拉选择框，暂时保持"距离最近"
                Log.info("点击了距离最近下拉框");
            });
        }

        // 设置滚动监听，实现分页加载
        if (parkingListScroll != null) {
            parkingListScroll.setReboundEffect(false);
            // 监听滚动到底部
            parkingListScroll.addScrolledListener(new Component.ScrolledListener() {
                @Override
                public void onContentScrolled(Component component, int x, int y, int oldX, int oldY) {
                    // 防抖：避免频繁触发
                    long currentTime = System.currentTimeMillis();
                    if (currentTime - lastLoadTime < LOAD_THROTTLE_MS) {
                        return;
                    }
                    
                    // 如果正在加载或没有更多数据，直接返回
                    if (isLoading || !hasMore) {
                        return;
                    }
                    
                    // 计算是否滚动到底部
                    int scrollY = parkingListScroll.getScrollValue(1);
                    int viewHeight = parkingListScroll.getHeight();
                    
                    // 获取内容高度（使用容器的高度）
                    int contentHeight = 0;
                    if (parkingListContainer != null) {
                        contentHeight = parkingListContainer.getHeight();
                    }
                    
                    // 如果容器高度为0，尝试使用EstimatedHeight
                    if (contentHeight == 0) {
                        contentHeight = parkingListScroll.getEstimatedHeight();
                    }
                    
                    // 如果内容高度或视图高度为0，无法计算，直接返回
                    if (contentHeight == 0 || viewHeight == 0) {
                        return;
                    }
                    
                    // 计算剩余滚动距离
                    int remainingDistance = contentHeight - scrollY - viewHeight;
                    
                    // 计算阈值（50像素，约等于50vp），当剩余距离小于等于阈值时触发加载
                    int threshold = 50;
                    
                    // 当滚动到底部（剩余距离小于等于阈值）时，触发加载
                    if (remainingDistance <= threshold && remainingDistance >= 0) {
                        lastLoadTime = currentTime;
                        // 加载下一页
                        loadParkingData(false);
                    }
                }
            });
        }

        // 默认选中全部车场
        switchTab(2);
    }

    /**
     * 切换标签页
     */
    private void switchTab(int filter) {
        filterType = filter;
        currentPage = 1;
        hasMore = true;
        lastLoadTime = 0; // 重置防抖时间
        parkingList.clear();
        if (parkingListContainer != null) {
            parkingListContainer.removeAllComponents();
        }
        
        // 更新标签样式
        Color selectedColor = new Color(Color.getIntColor("#FA6332"));
        Color normalColor = new Color(Color.getIntColor("#FF666666"));
        
        if (tabAll != null) {
            tabAll.setTextColor(filter == 2 ? selectedColor : normalColor);
        }
        if (tabRecommended != null) {
            tabRecommended.setTextColor(filter == 1 ? selectedColor : normalColor);
        }
        
        // 更新下划线显示
        if (tabAllUnderline != null) {
            tabAllUnderline.setVisibility(filter == 2 ? Component.VISIBLE : Component.HIDE);
        }
        if (tabRecommendedUnderline != null) {
            tabRecommendedUnderline.setVisibility(filter == 1 ? Component.VISIBLE : Component.HIDE);
        }
        
        // 加载数据
        loadParkingData(true);
    }

    /**
     * 加载停车场数据
     */
    private void loadParkingData(boolean isRefresh) {
        if (isLoading) {
            return;
        }

        if (isRefresh) {
            currentPage = 1;
            hasMore = true;
            lastLoadTime = 0; // 重置防抖时间
            parkingList.clear();
            if (parkingListContainer != null) {
                parkingListContainer.removeAllComponents();
            }
        }

        if (!hasMore) {
            return;
        }

        // 锁定当前页码，避免并发问题
        final int requestPage = currentPage;
        isLoading = true;

        // 获取定位坐标
        double latitude = 0;
        double longitude = 0;
        if (currentLocation != null) {
            latitude = currentLocation.getLatitude();
            longitude = currentLocation.getLongitude();
        }

        // 构建请求URL（使用锁定的页码）
        String url = String.format("/park/near/page?filter=%d&latitude=%f&longitude=%f&current=%d&size=%d",
                filterType, latitude, longitude, requestPage, pageSize);

        // 发送请求（网络请求已在后台线程）
        CompletableFuture<R<Object>> future = api.http(getContext(), url, "GET", null, null, null);
        future.thenAccept(response -> {
            // 在后台线程解析数据，避免阻塞UI
            try {
                if (response == null || !response.isSuccess()) {
                    String errorMsg = response != null ? response.getMsg() : "请求失败";
                    Log.error("加载停车场数据失败: " + errorMsg);
                    getUITaskDispatcher().asyncDispatch(() -> {
                        isLoading = false;
                        // 请求失败，保持currentPage不变，允许重试
                    });
                    return;
                }

                // 解析响应数据（在后台线程）
                Object dataObj = response.getData();
                if (dataObj == null) {
                    Log.error("响应数据为空");
                    getUITaskDispatcher().asyncDispatch(() -> {
                        isLoading = false;
                    });
                    return;
                }

                // 将data转换为ZSONObject
                ZSONObject pageObj;
                if (dataObj instanceof ZSONObject) {
                    pageObj = (ZSONObject) dataObj;
                } else {
                    pageObj = ZSONObject.stringToZSON(dataObj.toString());
                }

                // 解析Page对象（在后台线程）
                Page<ParkNearRes> page = parsePageData(pageObj);
                if (page == null || page.getRecords() == null) {
                    Log.error("解析分页数据失败");
                    getUITaskDispatcher().asyncDispatch(() -> {
                        isLoading = false;
                    });
                    return;
                }

                List<ParkNearRes> records = page.getRecords();
                if (records.isEmpty()) {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        isLoading = false;
                        hasMore = false;
                    });
                    return;
                }

                // 更新分页信息（在后台线程计算）
                boolean hasMoreData = true;
                int nextPage = requestPage + 1;
                if (page.getCurrent() != null && page.getPages() != null) {
                    int serverCurrent = page.getCurrent();
                    int totalPages = page.getPages();
                    if (serverCurrent >= totalPages) {
                        hasMoreData = false;
                    } else {
                        // 使用服务器返回的current值+1作为下一页
                        nextPage = serverCurrent + 1;
                    }
                } else {
                    if (records.size() < pageSize) {
                        hasMoreData = false;
                    }
                }

                // 保存最终的分页信息
                final boolean finalHasMore = hasMoreData;
                final int finalNextPage = nextPage;
                final List<ParkNearRes> finalRecords = records;

                // 只在UI线程更新界面
                getUITaskDispatcher().asyncDispatch(() -> {
                    isLoading = false;
                    
                    // 检查currentPage是否已经被其他请求更新（防止旧请求覆盖新数据）
                    // 如果currentPage > requestPage，说明有更新的请求已经完成，忽略这个旧请求的结果
                    if (currentPage > requestPage) {
                        Log.info("忽略过期请求，当前页码: " + currentPage + ", 请求页码: " + requestPage);
                        return;
                    }
                    
                    // 添加到列表
                    parkingList.addAll(finalRecords);
                    
                    // 批量渲染列表项（减少UI更新次数，延迟批量添加）
                    if (parkingListContainer != null && !finalRecords.isEmpty()) {
                        // 先批量创建所有组件
                        List<Component> items = new ArrayList<>();
                        for (ParkNearRes park : finalRecords) {
                            Component item = createParkingItem(park);
                            if (item != null) {
                                items.add(item);
                            }
                        }
                        
                        // 批量添加到容器（减少UI重绘次数）
                        for (Component item : items) {
                            parkingListContainer.addComponent(item);
                        }
                    }

                    // 更新分页信息
                    hasMore = finalHasMore;
                    if (finalHasMore) {
                        currentPage = finalNextPage;
                    }
                });

            } catch (Exception e) {
                Log.error("解析停车场数据失败: " + e.getMessage());
                e.printStackTrace();
                getUITaskDispatcher().asyncDispatch(() -> {
                    isLoading = false;
                });
            }
        });
    }

    /**
     * 解析分页数据
     */
    private Page<ParkNearRes> parsePageData(ZSONObject pageObj) {
        try {
            Page<ParkNearRes> page = new Page<>();
            
            if (pageObj.containsKey("total")) {
                page.setTotal(pageObj.getIntValue("total"));
            }
            if (pageObj.containsKey("pages")) {
                page.setPages(pageObj.getIntValue("pages"));
            }
            if (pageObj.containsKey("current")) {
                page.setCurrent(pageObj.getIntValue("current"));
            }
            if (pageObj.containsKey("size")) {
                page.setSize(pageObj.getIntValue("size"));
            }
            if (pageObj.containsKey("records")) {
                Object recordsObj = pageObj.get("records");
                if (recordsObj instanceof List) {
                    List<?> recordsList = (List<?>) recordsObj;
                    List<ParkNearRes> parkList = new ArrayList<>();
                    for (Object item : recordsList) {
                        ParkNearRes park = parseParkData(item);
                        if (park != null) {
                            parkList.add(park);
                        }
                    }
                    page.setRecords(parkList);
                }
            }
            
            return page;
        } catch (Exception e) {
            Log.error("解析Page数据失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 解析停车场数据
     */
    private ParkNearRes parseParkData(Object itemObj) {
        try {
            ZSONObject parkObj;
            if (itemObj instanceof ZSONObject) {
                parkObj = (ZSONObject) itemObj;
            } else {
                parkObj = ZSONObject.stringToZSON(itemObj.toString());
            }

            ParkNearRes park = new ParkNearRes();
            if (parkObj.containsKey("parkId")) {
                park.setParkId(parkObj.getString("parkId"));
            }
            if (parkObj.containsKey("parkName")) {
                park.setParkName(parkObj.getString("parkName"));
            }
            if (parkObj.containsKey("isreserver")) {
                park.setIsreserver(parkObj.getIntValue("isreserver"));
            }
            if (parkObj.containsKey("isfindcar")) {
                park.setIsfindcar(parkObj.getIntValue("isfindcar"));
            }
            if (parkObj.containsKey("powerEnable")) {
                park.setPowerEnable(parkObj.getIntValue("powerEnable"));
            }
            if (parkObj.containsKey("distance")) {
                park.setDistance(parkObj.getDoubleValue("distance"));
            }
            if (parkObj.containsKey("address")) {
                park.setAddress(parkObj.getString("address"));
            }
            if (parkObj.containsKey("totalPlace")) {
                park.setTotalPlace(parkObj.getIntValue("totalPlace"));
            }
            if (parkObj.containsKey("residuePlace")) {
                park.setResiduePlace(parkObj.getIntValue("residuePlace"));
            }
            if (parkObj.containsKey("latitude")) {
                park.setLatitude(parkObj.getDoubleValue("latitude"));
            }
            if (parkObj.containsKey("longitude")) {
                park.setLongitude(parkObj.getDoubleValue("longitude"));
            }
            if (parkObj.containsKey("onlinePayEnable")) {
                park.setOnlinePayEnable(parkObj.getIntValue("onlinePayEnable"));
            }
            if (parkObj.containsKey("invoiceEnable")) {
                park.setInvoiceEnable(parkObj.getIntValue("invoiceEnable"));
            }
            if (parkObj.containsKey("reductionEnable")) {
                park.setReductionEnable(parkObj.getIntValue("reductionEnable"));
            }
            if (parkObj.containsKey("chargeInfo")) {
                park.setChargeInfo(parkObj.getString("chargeInfo"));
            }

            return park;
        } catch (Exception e) {
            Log.error("解析ParkNearRes数据失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 创建停车场列表项组件（不添加到容器）
     */
    private Component createParkingItem(ParkNearRes park) {
        if (parkingListContainer == null) {
            return null;
        }

        try {
            // 加载列表项布局
            Component item = LayoutScatter.getInstance(this)
                    .parse(ResourceTable.Layout_item_parking, null, false);

            // 设置停车场名称
            Text nameText = (Text) item.findComponentById(ResourceTable.Id_parking_name);
            if (nameText != null && park.getParkName() != null) {
                nameText.setText(park.getParkName());
            }

            // 设置距离和地址
            Text addressText = (Text) item.findComponentById(ResourceTable.Id_parking_address);
            if (addressText != null) {
                String distanceStr = park.getDistance() != null ? 
                    String.format("%.1fkm", park.getDistance() / 1000.0) : "0km";
                String address = park.getAddress() != null ? park.getAddress() : "";
                addressText.setText(distanceStr + " | " + address);
            }

            // 设置总车位
            Text totalPlaceText = (Text) item.findComponentById(ResourceTable.Id_text_total_place);
            if (totalPlaceText != null && park.getTotalPlace() != null) {
                totalPlaceText.setText(String.valueOf(park.getTotalPlace()));
            }

            // 设置剩余车位
            Text residuePlaceText = (Text) item.findComponentById(ResourceTable.Id_text_residue_place);
            if (residuePlaceText != null && park.getResiduePlace() != null) {
                residuePlaceText.setText(String.valueOf(park.getResiduePlace()));
            }

            // 设置免费时长（从chargeInfo中解析，这里简化处理）
            Text freeDurationText = (Text) item.findComponentById(ResourceTable.Id_text_free_duration);
            if (freeDurationText != null) {
                // 这里可以根据chargeInfo解析免费时长，暂时显示"15分"
                freeDurationText.setText("15分");
            }

            // 设置标签
            DirectionalLayout tagsContainer = (DirectionalLayout) item.findComponentById(ResourceTable.Id_tags_container);
            if (tagsContainer != null) {
                tagsContainer.removeAllComponents();
                
                // 根据数据添加标签
                // 商场、学校等标签需要根据业务逻辑判断，这里简化处理
                // 可预约 - 浅蓝色（#4CAF50 或 #2196F3）
                if (park.getIsreserver() != null && park.getIsreserver() == 1) {
                    addTag(tagsContainer, "可预约", "#4CAF50");
                }
                // 可充电 - 浅蓝色
                if (park.getPowerEnable() != null && park.getPowerEnable() == 1) {
                    addTag(tagsContainer, "可充电", "#4CAF50");
                }
                // 优惠 - 红色
                if (park.getReductionEnable() != null && park.getReductionEnable() == 1) {
                    addTag(tagsContainer, "惠", "#FF0000");
                }
                // 商场、学校等标签 - 橙色（#FA6332，需要根据业务逻辑判断，这里暂时不添加）
            }

            // 设置导航按钮点击事件
            Image navButton = item.findComponentById(ResourceTable.Id_btn_navigate);
            if (navButton != null) {
                navButton.setClickedListener(component -> {
                    // 导航功能
                    Log.info("导航到: " + park.getParkName());
                    // TODO: 实现导航功能
                });
            }

            return item;

        } catch (Exception e) {
            Log.error("创建停车场列表项失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加停车场列表项（兼容方法，内部调用createParkingItem）
     */
    private void addParkingItem(ParkNearRes park) {
        Component item = createParkingItem(park);
        if (item != null && parkingListContainer != null) {
            parkingListContainer.addComponent(item);
        }
    }

    /**
     * 添加标签
     */
    private void addTag(DirectionalLayout container, String text, String bgColor) {
        Text tag = new Text(getContext());
        tag.setText(text);
        tag.setTextSize(11);
        tag.setTextColor(Color.WHITE);
        tag.setPadding(8, 4, 8, 4);
        
        // 创建圆角背景（椭圆形）
        ShapeElement background = new ShapeElement();
        background.setShape(ShapeElement.RECTANGLE);
        RgbColor rgbColor = new RgbColor(Color.getIntColor(bgColor));
        background.setRgbColor(rgbColor);
        background.setCornerRadius(12);
        tag.setBackground(background);
        
        tag.setMarginLeft(4);
        container.addComponent(tag);
    }
}
