// pages/tixian/tixian.js
import request from '../../utils/request.js';
import PopupService from '../../services/popupService.js';

const app = getApp();

Page({
    data: {
        pageMode: 0,       // 0:加载中  1:收款码模式  2:微信零钱模式
        pageOptions: {},   // 保存启动参数，传给子组件
        loadError: false,  // 获取模式失败时展示错误状态
    },

    onLoad(options) {
        this.setData({
            pageOptions: options || {}
        });
        this.fetchPageMode();
    },

    // ✅ 用 onShow，别用 pageLifetimes
    onShow() {
        this.registerNotificationComponent();
        // 如果已经在某个模式下，可以刷新一下子组件数据（可选）
        // 弹窗检查
        PopupService.checkAndShow(this, 'tixian');
    },

    onHide() {
        const popupComp = this.selectComponent('#popupNotice');
        if (popupComp && popupComp.cleanup) {
            popupComp.cleanup();
        }
    },

    // ✅ 注册通知组件（弹窗依赖它）
    registerNotificationComponent() {
        const notificationComp = this.selectComponent('#global-notification');
        if (notificationComp && notificationComp.showNotification) {
            app.globalData.globalNotification = {
                show: (data) => notificationComp.showNotification(data),
                hide: () => notificationComp.hideNotification()
            };
        }
    },

    async fetchPageMode() {
        try {
            const res = await request({
                url: '/peizhi/hqtxzsym',
                method: 'POST'
            });

            if (res.statusCode === 200 && res.data && res.data.code === 0) {
                const mode = parseInt(res.data.data.mode);
                this.setData({
                    pageMode: (mode === 1 || mode === 2) ? mode : 1,
                    loadError: false
                });
            } else {
                this.setData({ pageMode: 1, loadError: false });
            }
        } catch (err) {
            console.error('获取展示模式失败:', err);
            this.setData({ loadError: true });
        }
    },

    retryFetch() {
        this.setData({ loadError: false, pageMode: 0 });
        this.fetchPageMode();
    },

    stopPropagation() {}
});