// app.js - 优化生产版本（修复重连机制和用户ID问题）
import { check } from './utils/phone-auth';

// 【聊天总开关】GoEasy 续费/开通后保持 true；未开通时改为 false 避免 SDK 报错
const IM_SERVICE_ENABLED = true;


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

// 【暂时下线】组长/考核官身份已统一迁移为打手
const DEPRECATED_ROLES = ['zuzhang', 'kaoheguan'];

App({
    globalData: {

        hasShownPopupOnColdStart: false,

        apiBaseUrl: 'https://wenhe.nmslb.com/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:'wx568f9b618bfa7578',
        
        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: ''
        },
        
        paihangAssets: null,
        pageAssets: null,
        xshenfen: 1,
        
        goEasyConfig: null,
        chatEnabled: false,
        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();
        });

        this.initChatStubs();

        // 冷启动进入商城首页，但保留身份用于 IM（勿把 currentRole 强行改成 normal）
        const savedRole = wx.getStorageSync('currentRole') || 'normal';
        const normalizedRole = this.normalizeRole(savedRole);
        this.globalData.currentRole = normalizedRole;
        wx.setStorageSync('currentRole', normalizedRole);

        setTimeout(() => {
            wx.reLaunch({ url: '/pages/index/index' });
        }, 0);

        this.fetchDynamicConfig()
            .then(config => {
                this.applyDynamicConfig(config);
                if (IM_SERVICE_ENABLED) {
                    this.initGoEasyWithConfig();
                    const ChatCore = require('./utils/chat-core');
                    ChatCore.initGlobalMessageSystem(this);
                    this.bootstrapImListening();
                }
                this.initCurrentUser();
            })
            .catch(error => {
                console.error('获取动态配置失败:', error);
                this.initCurrentUser();
            });

        try {
            const needAuth = await check();
            if (needAuth) {
                wx.reLaunch({ url: '/pages/phone-auth/phone-auth' });
                return;
            }
        } catch (e) {}
    },

    onShow() {
        if (this.globalData.chatEnabled && typeof this.ensureConnection === 'function') {
            this.ensureConnection();
        }
    },

  /** 配置加载完成后立即启动 IM 监听（有 uid 即连） */
    bootstrapImListening() {
        const uid = wx.getStorageSync('uid');
        if (!uid || !this.globalData.chatEnabled) return;
        try {
            this.ensureConnection();
        } catch (e) {
            console.warn('IM 启动失败:', e);
        }
    },

    initChatStubs() {
        this.globalData.chatEnabled = false;
        wx.goEasy = null;
        this.disconnectGoEasy = () => Promise.resolve();
        this.ensureConnection = () => {};
        this.connectWithIdentity = () => Promise.reject(new Error('聊天未启用'));
        this.connectForCurrentRole = () => {};
        this.switchRoleAndReconnect = () => Promise.resolve(false);
        this.loadConversations = () => {};
        this.updateUnreadCount = () => {};
        this.getSavedConnection = () => null;
        this.clearSavedConnection = () => {};
        this.saveConnectionState = () => {};
        this.handleNewMessage = () => {};
        this.toggleDoNotDisturb = () => {};
        this.toggleNotificationMute = () => {};
        this.closeNotification = () => {};
        this.updateCurrentPageState = () => {};
    },

    
    
    
    // 以下三个方法完全保持原样
    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 >= 500) {
                        reject(new Error('服务器错误 ' + res.statusCode));
                        return;
                    }
                    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 || '';
            this.globalData.paihangAssets = config.otherConfig.paihangAssets || null;
        }
        if (config.pageAssets) {
            this.globalData.pageAssets = config.pageAssets;
        }
        if (config.kefu) {
            this.globalData.kefuConfig = {
                link: config.kefu.link || '',
                enterpriseId: config.kefu.enterpriseId || ''
            };
        }
    },
    
    initGoEasyWithConfig() {
        if (!IM_SERVICE_ENABLED) return;
        const GoEasy = require('./static/lib/goeasy-2.13.24.esm.min').default;
        wx.GoEasy = GoEasy;
        const cfg = this.globalData.goEasyConfig;
        if (!cfg || !cfg.appkey) {
            this.globalData.chatEnabled = false;
            return;
        }
        try {
            wx.goEasy = GoEasy.getInstance({
                host: cfg.host || 'hangzhou.goeasy.io',
                appkey: cfg.appkey,
                modules: ['im', 'pubsub']
            });
            const imReady = !!(wx.goEasy?.im && typeof wx.goEasy.im.on === 'function');
            this.globalData.chatEnabled = imReady;
            if (!imReady) {
                wx.goEasy = null;
            }
        } catch (e) {
            console.warn('GoEasy 初始化失败:', e);
            this.globalData.chatEnabled = false;
            wx.goEasy = null;
        }
    },

    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);
            }
        }
    },

    normalizeRole(role) {
        if (DEPRECATED_ROLES.includes(role)) return 'dashou';
        return role || 'normal';
    },

    getDashouEntryPage() {
        return '/pages/jiedan/jiedan';
    }
});