package com.fujica.abk.slice;

import com.fujica.abk.ResourceTable;
import com.fujica.abk.api.auth;
import com.fujica.abk.api.cache;
import com.fujica.abk.common.EventBus;
import com.fujica.abk.component.LoadingComponent;
import com.fujica.abk.component.OrderDetailComponent;
import com.fujica.abk.component.ParkDetailComponent;
import com.fujica.abk.component.nav.ChargeComponent;
import com.fujica.abk.component.nav.OrderComponent;
import com.fujica.abk.component.nav.ParkComponent;
import com.fujica.abk.model.out.OrderRes;
import com.fujica.abk.model.out.ParkNearRes;
import com.fujica.abk.utils.DialogUtil;
import com.fujica.abk.utils.Log;
import com.fujica.abk.utils.Toast;
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.content.Intent;
import ohos.agp.components.*;
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;

public class MainAbilitySlice extends AbilitySlice {
    // 页面容器
    private StackLayout pageContainer;

    // 底部导航栏组件
    private DirectionalLayout navCharge;
    private DirectionalLayout navPark;
    private DirectionalLayout navOrder;
    private DirectionalLayout navCurrentLocation;

    // 底部导航栏文字和图标
    private Text textCharge;
    private Text textPark;
    private Text textOrder;
    private Image iconPark;
    private Image iconPark1;
    private Image iconCharge;
    private Image iconCharge1;
    private Image iconOrder;
    private Image iconOrder1;

    // 当前选中的 tab
    private int currentTab = 0; // 0: 找车位, 1: 计费, 2: 缴费记录

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

    // 页面组件
    private ChargeComponent chargeComponent;
    private ParkComponent parkComponent; // 找车位页面组件
    private OrderComponent orderComponent; // 缴费记录页面组件
    
    // 页面初始化标志
    private boolean isChargeComponentInitialized = false;
    private boolean isParkComponentInitialized = false;
    private boolean isOrderComponentInitialized = false;

    // 详情区域
    private DirectionalLayout mainRight; // 右侧详情区域
    private OrderDetailComponent orderDetailComponent; // 订单详情组件
    private ParkDetailComponent parkDetailComponent; // 停车场详情组件

    // Loading组件
    private LoadingComponent loadingComponent;

    // 登录成功事件监听器
    private EventBus.EventListener loginSuccessListener;
    // 认证状态变化事件监听器
    private EventBus.EventListener authChangedListener;

    private Image quit;

    @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) {
        }

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

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

        // 初始化Loading组件并添加到根布局
        loadingComponent = findComponentById(ResourceTable.Id_loading_component);

        // 初始化详情区域
        mainRight = findComponentById(ResourceTable.Id_main_right);
        if (mainRight != null) {
            // 创建详情组件
            orderDetailComponent = new OrderDetailComponent(this);
            parkDetailComponent = new ParkDetailComponent(this);
        }

        quit = findComponentById(ResourceTable.Id_quit);
        quit.setClickedListener(v -> {
            DialogUtil.confirm(getContext(), "确认要退出吗？", () -> {
                cache.logout(getContext());
                quit.setVisibility(Component.HIDE);
            });
        });
        quit.setVisibility(cache.isAuth(getContext()) ? Component.VISIBLE : Component.HIDE);

        // 初始化组件
        initComponents();

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

        // 初始化定位
        initLocation();

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

        // 订阅登录成功事件
        subscribeLoginSuccessEvent();
        // 订阅认证状态变化事件
        subscribeAuthChangedEvent();
    }

    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() {
        // 初始化页面容器
        pageContainer = findComponentById(ResourceTable.Id_page_container);

        // 初始化底部导航栏
        initBottomNavigation();
        
        // 默认初始化找车位页面（因为默认显示该页面）
//        initParkComponent();

        // 默认选中找车位
        switchToPage(0);
    }

    /**
     * 初始化缴费页面组件
     */
    private void initChargeComponent() {
        if (isChargeComponentInitialized || pageContainer == null) {
            return;
        }
        
        try {
            Log.info("首次初始化缴费页面");
            chargeComponent = new ChargeComponent(MainAbilitySlice.this);
            chargeComponent.setLoadingComponent(loadingComponent);
            chargeComponent.setVisibility(Component.HIDE);
            pageContainer.addComponent(chargeComponent);
            isChargeComponentInitialized = true;
            Log.info("缴费页面初始化完成");
        } catch (Exception e) {
            Log.error("创建缴费页面组件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 初始化找车位页面组件
     */
    private void initParkComponent() {
        if (isParkComponentInitialized || pageContainer == null) {
            return;
        }
        
        try {
            Log.info("首次初始化找车位页面");
            parkComponent = new ParkComponent(MainAbilitySlice.this);
            parkComponent.setLoadingComponent(loadingComponent);
            // 如果已有定位信息，设置到组件中
            if (currentLocation != null) {
                parkComponent.setCurrentLocation(currentLocation);
            }
            // 设置停车场选中监听器
            parkComponent.setOnParkSelectedListener(new ParkComponent.OnParkSelectedListener() {
                @Override
                public void onParkSelected(ParkNearRes park) {
                    showParkDetail(park);
                }

                @Override
                public void onParkDeselected() {
                    hideDetail();
                }
            });
            parkComponent.setVisibility(Component.HIDE);
            pageContainer.addComponent(parkComponent);
            isParkComponentInitialized = true;
            Log.info("找车位页面初始化完成");
        } catch (Exception e) {
            Log.error("创建找车位页面组件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 初始化缴费记录页面组件
     */
    private void initOrderComponent() {
        if (isOrderComponentInitialized || pageContainer == null) {
            return;
        }
        
        try {
            Log.info("首次初始化缴费记录页面");
            orderComponent = new OrderComponent(MainAbilitySlice.this);
            orderComponent.setLoadingComponent(loadingComponent);
            // 设置订单选中监听器
            orderComponent.setOnOrderSelectedListener(new OrderComponent.OnOrderSelectedListener() {
                @Override
                public void onOrderSelected(OrderRes order) {
                    showOrderDetail(order);
                }

                @Override
                public void onOrderDeselected() {
                    hideDetail();
                }
            });
            orderComponent.setVisibility(Component.HIDE);
            pageContainer.addComponent(orderComponent);
            isOrderComponentInitialized = true;
            Log.info("缴费记录页面初始化完成");
        } catch (Exception e) {
            Log.error("创建缴费记录页面组件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 初始化底部导航栏
     */
    private void initBottomNavigation() {
        navCharge = findComponentById(ResourceTable.Id_nav_charge);
        navPark = findComponentById(ResourceTable.Id_nav_find_parking);
        navOrder = findComponentById(ResourceTable.Id_nav_order);
        navCurrentLocation = findComponentById(ResourceTable.Id_nav_current_location);

        textCharge = findComponentById(ResourceTable.Id_text_charge);
        textPark = findComponentById(ResourceTable.Id_text_park);
        textOrder = findComponentById(ResourceTable.Id_text_order);
        iconPark = findComponentById(ResourceTable.Id_icon_park);
        iconPark1 = findComponentById(ResourceTable.Id_icon_park_1);
        iconCharge = findComponentById(ResourceTable.Id_icon_charge);
        iconCharge1 = findComponentById(ResourceTable.Id_icon_charge_1);
        iconOrder = findComponentById(ResourceTable.Id_icon_order);
        iconOrder1 = findComponentById(ResourceTable.Id_icon_order_1);

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

    private void switchToPageAfterLogin(int index){
        // 先检查是否已登录
        if (!cache.isAuth(this)) {
            // 未登录，调用登录方法
            Log.info("未登录，开始登录流程");
            auth.login(this).thenAccept(success -> {
                if (success) {
                    // 登录成功后切换到缴费记录页面
                    DialogUtil.postTask(() -> switchToPage(index));
                } else {
                    Toast.error(this, "登录失败，请重试");
                }
            }).exceptionally(e -> {
                Log.error("登录异常: " + e.getMessage());
                e.printStackTrace();
                Toast.error(this, "登录异常: " + e.getMessage());
                return null;
            });
        } else {
            // 已登录，直接切换页面
            switchToPage(index);
        }
    }


    /**
     * 切换到指定页面
     */
    private void switchToPage(int index) {
        if (index < 0 || index > 2) {
            return;
        }

        // 隐藏所有页面
        if (chargeComponent != null) {
            chargeComponent.setVisibility(Component.HIDE);
        }
        if (parkComponent != null) {
            parkComponent.setVisibility(Component.HIDE);
        }
        if (orderComponent != null) {
            orderComponent.setVisibility(Component.HIDE);
        }

        // 显示目标页面
        switch (index) {
            case 0: // 找车位
                // 首次打开时初始化
                if (!isParkComponentInitialized) {
                    initParkComponent();
                    // 首次初始化时，组件内部已经加载了数据，无需再调用refresh()
                } else if (parkComponent != null) {
                    // 非首次打开时才刷新数据
                    parkComponent.refresh();
                }
                if (parkComponent != null) {
                    parkComponent.setVisibility(Component.VISIBLE);
                }
                break;
            case 1: // 计费
                // 首次打开时初始化
                if (!isChargeComponentInitialized) {
                    initChargeComponent();
                    // 首次初始化时，组件内部已经加载了数据，无需再调用refresh()
                } else if (chargeComponent != null) {
                    // 非首次打开时才刷新数据
                    chargeComponent.refresh();
                }
                if (chargeComponent != null) {
                    chargeComponent.setVisibility(Component.VISIBLE);
                }
                break;
            case 2: // 缴费记录
                // 首次打开时初始化
                if (!isOrderComponentInitialized) {
                    initOrderComponent();
                    // 首次初始化时，组件内部已经加载了数据，无需再调用reset()
                } else if (orderComponent != null) {
                    // 非首次打开时才刷新数据
                    orderComponent.reset();
                }
                if (orderComponent != null) {
                    orderComponent.setVisibility(Component.VISIBLE);
                }
                break;
        }

        // 更新当前tab状态
        currentTab = index;
        updateBottomNavState(index);

        // 切换页面时隐藏详情
        hideDetail();
    }

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

        if (textCharge != null) {
            textCharge.setTextColor(grayColor);
        }
        if (textPark != null) {
            textPark.setTextColor(grayColor);
        }
        if (textOrder != null) {
            textOrder.setTextColor(grayColor);
        }

        // 设置选中状态
        switch (index) {
            case 0: // 找车位
                textPark.setTextColor(blueColor);

                iconCharge.setVisibility(Component.VISIBLE);
                iconCharge1.setVisibility(Component.HIDE);
                iconOrder.setVisibility(Component.VISIBLE);
                iconOrder1.setVisibility(Component.HIDE);
                iconPark.setVisibility(Component.HIDE);
                iconPark1.setVisibility(Component.VISIBLE);
                break;
            case 1: // 我的
                textCharge.setTextColor(blueColor);

                iconCharge.setVisibility(Component.HIDE);
                iconCharge1.setVisibility(Component.VISIBLE);
                iconOrder.setVisibility(Component.VISIBLE);
                iconOrder1.setVisibility(Component.HIDE);
                iconPark.setVisibility(Component.VISIBLE);
                iconPark1.setVisibility(Component.HIDE);
                break;
            case 2: // 缴费记录
                textOrder.setTextColor(blueColor);

                iconCharge.setVisibility(Component.VISIBLE);
                iconCharge1.setVisibility(Component.HIDE);
                iconOrder.setVisibility(Component.HIDE);
                iconOrder1.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 == 0 && parkComponent != null) {
                        parkComponent.setCurrentLocation(location);
                    }
                }

                @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());
        }
    }


    /**
     * 订阅登录成功事件
     */
    private void subscribeLoginSuccessEvent() {
        loginSuccessListener = event -> {
            // 在主线程更新UI
            DialogUtil.postTask(() -> {
                // 刷新我的页面
                if (chargeComponent != null) {
                    chargeComponent.refresh();
                }
                quit.setVisibility(Component.VISIBLE);
                // 可以在这里添加其他需要更新的UI逻辑
            });
        };
        EventBus.getInstance().on("onLoginSuccess", loginSuccessListener);
    }

    /**
     * 订阅认证状态变化事件
     */
    private void subscribeAuthChangedEvent() {
        authChangedListener = event -> {
            // 在主线程更新UI
            DialogUtil.postTask(() -> {
                Log.error("收到认证状态变化事件，更新UI");
                // 隐藏退出按钮
                if (quit != null) {
                    quit.setVisibility(Component.HIDE);
                }
                // 刷新我的页面
                if (chargeComponent != null) {
                    chargeComponent.refresh();
                }
                // 可以在这里添加其他需要更新的UI逻辑
            });
                // 认证过期后重新登录
                auth.login(MainAbilitySlice.this).thenAccept(success -> {
                    if (success) {
                        Log.info("重新登录成功");
                    } else {
                        Log.error("重新登录失败");
                    }
                }).exceptionally(e -> {
                    Log.error("重新登录异常: " + e.getMessage());
                    return null;
                });
        };
        EventBus.getInstance().on("onLoginExpired", authChangedListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 取消订阅登录成功事件
        if (loginSuccessListener != null) {
            EventBus.getInstance().off("onLoginSuccess", loginSuccessListener);
        }
        // 取消订阅认证状态变化事件
        if (authChangedListener != null) {
            EventBus.getInstance().off("onLoginExpired", authChangedListener);
        }

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

    /**
     * 显示订单详情
     */
    private void showOrderDetail(OrderRes order) {
        if (mainRight == null || orderDetailComponent == null) {
            return;
        }
        // 移除所有子组件
        mainRight.removeAllComponents();
        // 设置订单数据
        orderDetailComponent.setOrderData(order,getContext());
        // 添加详情组件
        mainRight.addComponent(orderDetailComponent);
        // 显示详情区域
        mainRight.setVisibility(Component.VISIBLE);
    }

    /**
     * 显示停车场详情
     */
    private void showParkDetail(ParkNearRes park) {
        if (mainRight == null || parkDetailComponent == null) {
            return;
        }
        // 移除所有子组件
        mainRight.removeAllComponents();
        // 设置停车场数据
        parkDetailComponent.setParkData(park);
        // 添加详情组件
        mainRight.addComponent(parkDetailComponent);
        // 显示详情区域
        mainRight.setVisibility(Component.VISIBLE);
    }

    /**
     * 隐藏详情
     */
    private void hideDetail() {
        if (mainRight == null) {
            return;
        }
        // 移除所有子组件
        mainRight.removeAllComponents();
        // 隐藏详情区域
        mainRight.setVisibility(Component.HIDE);
    }

}
