// app.js - 优化生产版本（修复重连机制和用户ID问题）
import GoEasy from './static/lib/goeasy-2.13.24.esm.min';
const ChatCore = require('./utils/chat-core');
import { check } from './utils/phone-auth';


// ===== 角色 → 默认首页（与 custom-tab-bar 完全一致） =====
const roleDefaultPage = {
  normal:      '/pages/index/index',
  dashou:      '/pages/dashouduan/dashouduan',
  shangjia:    '/pages/shangjiaduan/shangjiaduan',          // 商家首页也是商城
  guanshi:     '/pages/guanshiduan/guanshiduan',
  zuzhang:     '/pages/zuzhangduan/zuzhangduan',
  kaoheguan: '/pages/kaoheguan/kaoheguan'
};

App({
    globalData: {

        hasShownPopupOnColdStart: false,

        apiBaseUrl: 'https://6ccy.top/hqhd',
        ossImageUrl: '',
        morentouxiang: '',
        dashouguize: '',

        shangpinliebiao: [],
        shangpinzhuanqu: [],
        shangpinleixing: [],
        shangpinlunbo: [],
        shangpingonggao: '',
        lunbozhanwei: '/images/lunbozhanwei.jpg',
        
        dingdanTiaoshu: {
            daifuwu: 0,
            fuwuzhong: 0,
            yiwancheng: 0,
            yituikuan: 0
        },
        
        dashouqun: '',
        dashouqunid: '',
        guanshiqun: '',
        guanshiqunid: '',
            
        appId:'wx2517043ca3f39677',
        
        shangjiastatus: 0,
        dashoustatus: 0,
        guanshistatus: 0,
        dashouNicheng: '',
        zhanghaoStatus: null,
        dashouzhuangtai: null,
        yongjin: null,
        zonge: null,
        yajin: null,
        chenghao: '',
        jinfen: null,
        clumber: [{
            huiyuanid: '',
            huiyuanming: '',
            daoqi: ''
        }],
        chengjiaoliang: null,
        zaixianZhuangtai: null,
        
        guanshi: {
            nicheng: '',
            uid: '',
            touxiang: '',
            gszhstatus: '',
            yaoqingzongshu: 0,
            fenyongzonge: '0.00',
            fenyongtixian: '0.00'
        },
        
        shangjia: {
            sjzhzhuangtai: '',
            sjyue: '',
            fadanzong: null,
            tuikuanzong: null,
            riliushui: '',
            yueliushui: ''
        },
        
        liaotian_liebiao: [],
        xshenfen: 1,
        
        goEasyConfig: null,
        kefuConfig: {
            link: '',
            enterpriseId: ''
        },
        
        cosConfig: {
            bucket: '',
            region: 'ap-shanghai',
            uploadPathPrefix: 'order/'
        },
        
        goEasyConnection: {
            status: 'disconnected',
            userId: '',
            identityType: '',
            lastConnectTime: 0,
            autoReconnect: true,
            reconnectAttempts: 0,
            maxReconnectAttempts: 5,
            heartbeatInterval: null,
            cacheKeys: {
                savedConnection: 'savedGoEasyConnection',
                userId: 'goEasyUserId',
                identityType: 'currentGoEasyIdentity',
                connectTime: 'goEasyConnectTime'
            },
            config: {
                heartbeatInterval: 20000,
                reconnectDelay: 3000,
                offlineTimeout: 30000,
                cacheValidityHours: 12
            }
        },
        
        messageManager: {
            unreadTotal: 0,
            unreadMap: {},
            latestMessages: [],
            notificationQueue: [],
            notificationVisible: false,
            lastNotificationTime: 0,
            notificationCooldown: 3000,
            tabBarIndex: 2,
            showTabBarBadge: true,
            customTabBar: true,
            tabBarBadgeText: 0,
            soundEnabled: true,
            vibrationEnabled: true,
            doNotDisturb: false,
            doNotDisturbStart: '22:00',
            doNotDisturbEnd: '08:00',
            notificationStyle: {
                position: 'top',
                duration: 3000,
                backgroundColor: '#00f7ff',
                textColor: '#ffffff',
                borderRadius: '16rpx',
                boxShadow: '0 10rpx 30rpx rgba(0, 247, 255, 0.3)'
            },
            currentNotification: null,
            cacheKeys: {
                messageSettings: 'messageSettings',
                unreadTotal: 'messageUnreadTotal',
                latestMessages: 'latestMessages',
                notificationMuted: 'notificationMuted'
            }
        },
        
        pageState: {
            currentPage: '',
            isInChatPage: false,
            currentChatId: '',
            lastPageUpdate: 0
        },
        
        eventListeners: {},
        debugMode: false,
        currentUser: null,
        currentRole: 'normal'            // 当前角色，默认老板
    },
    
    // ========== 仅修改 onLaunch，其余未动 ==========
    async onLaunch() {
        // ---------- ① 立即隐藏“返回首页”按钮 ----------
        wx.hideHomeButton();
        wx.onAppRoute(() => {
            wx.hideHomeButton();
        });
        // 🆕 手机号认证检查
  

        // ---------- ② 恢复角色并跳转（不依赖网络） ----------
        const savedRole = wx.getStorageSync('currentRole') || 'normal';
        this.globalData.currentRole = savedRole;

        const targetPage = roleDefaultPage[savedRole] || '/pages/index/index';
        if (savedRole !== 'normal' || targetPage !== '/pages/index/index') {
            setTimeout(() => {
                wx.reLaunch({ url: targetPage });
            }, 0);
        }

        // ---------- ③ 后台静默获取配置，成功后再初始化 GoEasy/IM ----------
        this.fetchDynamicConfig()
            .then(config => {
                this.applyDynamicConfig(config);
                this.initGoEasyWithConfig();
                ChatCore.initGlobalMessageSystem(this);
                this.initCurrentUser();

                const saved = this.getSavedConnection();
                console.log('【app.js启动】缓存身份:', saved ? saved.identityType : '无',
                            'userId:', saved ? saved.userId : '无');
                setTimeout(() => {
                    this.ensureConnection();
                }, 300);
            })
            .catch(error => {
                console.error('获取动态配置失败:', error);
                
                // 兜底初始化，防止后续调用报错
                this.initGoEasyWithConfig();
                ChatCore.initGlobalMessageSystem(this);
                this.initCurrentUser();
            });


            // ---------- ④ 所有初始化完成后，最后进行手机号认证检查 ----------
            try {
                const needAuth = await check();   // 你已经顶部 import 了
                if (needAuth) {
                    wx.reLaunch({ url: '/pages/phone-auth/phone-auth' });
                    return;
                }
            } catch (e) {}
        
    },

    
    
    
    // 以下三个方法完全保持原样
    fetchDynamicConfig() {
        return new Promise((resolve, reject) => {
            wx.request({
                url: this.globalData.apiBaseUrl + '/peizhi/qdpzhq',
                method: 'POST',
                header: { 'content-type': 'application/json' },
                success: (res) => {
                    if (res.statusCode === 200 && res.data && res.data.code === 0) {
                        resolve(res.data.data);
                    } else {
                        reject(new Error(res.data?.msg || '接口返回错误'));
                    }
                },
                fail: reject
            });
        });
    },
    
    applyDynamicConfig(config) {
        if (config.cos) {
            this.globalData.ossImageUrl = config.cos.ossImageUrl || '';
            this.globalData.cosConfig = {
                bucket: config.cos.bucket || '',
                region: config.cos.region || 'ap-shanghai',
                uploadPathPrefix: config.cos.uploadPathPrefix || 'order/'
            };
        }
        if (config.goEasy) {
            this.globalData.goEasyConfig = {
                host: config.goEasy.host || 'hangzhou.goeasy.io',
                appkey: config.goEasy.appkey || ''
            };
        }
        if (config.otherConfig) {
            this.globalData.morentouxiang = config.otherConfig.morentouxiang || '';
            this.globalData.dashouguize = config.otherConfig.dashouguize || '';
        }
        if (config.kefu) {
            this.globalData.kefuConfig = {
                link: config.kefu.link || '',
                enterpriseId: config.kefu.enterpriseId || ''
            };
        }
    },
    
    initGoEasyWithConfig() {
        const cfg = this.globalData.goEasyConfig;
        if (!cfg || !cfg.appkey) {
            console.error('GoEasy appkey 未配置，无法初始化');
            return;
        }
        wx.goEasy = GoEasy.getInstance({
            host: cfg.host || 'hangzhou.goeasy.io',
            appkey: cfg.appkey,
            modules: ['im', 'pubsub']
        });
        wx.GoEasy = GoEasy;
    },
    
    initCurrentUser() {
        const uid = wx.getStorageSync('uid');
        if (uid) {
            this.globalData.currentUser = {
                id: uid,
                name: '用户' + uid.substring(0, 6),
                avatar: this.globalData.ossImageUrl + this.globalData.morentouxiang
            };
        }
    },
    
    emitEvent(eventName, data) {
        if (this.globalData.eventListeners[eventName]) {
            this.globalData.eventListeners[eventName].forEach(callback => {
                try { callback(data); } catch (error) { console.error(error); }
            });
        }
    },
    
    on(eventName, callback) {
        if (!this.globalData.eventListeners[eventName]) {
            this.globalData.eventListeners[eventName] = [];
        }
        this.globalData.eventListeners[eventName].push(callback);
    },
    
    off(eventName, callback) {
        if (this.globalData.eventListeners[eventName]) {
            const index = this.globalData.eventListeners[eventName].indexOf(callback);
            if (index > -1) {
                this.globalData.eventListeners[eventName].splice(index, 1);
            }
        }
    }
});