// const TelegramBot = require('node-telegram-bot-api');
// const express = require('express');
// const fs = require('fs');
// const moment = require('moment');
// const config = require('./config');
// const { createGroup, updateGroup } = require('./admin/controllers/groupController');

// // 初始化数据存储
// let data = {
//     deposits: [], // 入款记录
//     withdrawals: [], // 下发记录
//     lastUpdate: null,
//     allowedGroups: ['4754375683'] // 允许使用的群组ID
// };

// // 加载数据
// function loadData() {
//     try {
//         if (fs.existsSync(config.DB_FILE)) {
//             const savedData = JSON.parse(fs.readFileSync(config.DB_FILE));
//             data = { ...data, ...savedData };
//         }
//     } catch (error) {
//         console.error('Error loading data:', error);
//     }
// }

// // 保存数据
// function saveData() {
//     try {
//         fs.writeFileSync(config.DB_FILE, JSON.stringify(data, null, 2));
//     } catch (error) {
//         console.error('Error saving data:', error);
//     }
// }

// // 创建机器人实例
// const bot = new TelegramBot(config.BOT_TOKEN, { polling: true });

// // 创建Express应用
// const app = express();

// // 检查群组权限
// function isGroupAllowed(chatId) {
//     const chatIdStr = chatId.toString();
//     return data.allowedGroups.includes(chatIdStr) || 
//            data.allowedGroups.includes(chatIdStr.replace('-', ''));
// }

// // 检查是否是管理员
// function isAdmin(userId) {
//     return config.ADMIN_IDS.includes(userId.toString());
// }

// // 处理新成员加入
// bot.on('new_chat_members', async (msg) => {
//     const chatId = msg.chat.id;
//     const newMembers = msg.new_chat_members;
    
//     for (const member of newMembers) {
//         if (member.id === (await bot.getMe()).id) {
//             // 机器人被添加到群组
//             console.log(`机器人被添加到群组: ${chatId}`);
            
//             // 检查群组是否在允许列表中
//             const chatIdStr = chatId.toString();
//             if (!data.allowedGroups.includes(chatIdStr)) {
//                 try {
//                     // 使用 createGroup 创建新群组
//                     const groupData = {
//                         groupId: chatIdStr,
//                         groupName: msg.chat.title || '未命名群组',
//                         groupType: msg.chat.type === 'private' ? 'personal' : 'public'
//                     };
                    
//                     const result = await createGroup({ body: groupData });
//                     if (result) {
//                         // 更新内存中的群组列表
//                         data.allowedGroups.push(chatIdStr);
//                         saveData();
//                         sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。');
//                     } else {
//                         sendMessage(chatId, '添加群组失败,请联系管理员。');
//                     }
//                 } catch (error) {
//                     console.error('创建群组失败:', error);
//                     sendMessage(chatId, '添加群组失败,请联系管理员。');
//                 }
//             } else {
//                 sendMessage(chatId, '感谢添加我为群组成员!使用 /help 查看可用命令。');
//             }
//         } else {
//             // 其他新成员
//             console.log(`新成员加入群组: ${member.username || member.first_name} (${member.id})`);
//             sendMessage(chatId, `欢迎 ${member.username || member.first_name} 加入群组!`);
//         }
//     }
// });

// // 处理成员离开
// bot.on('left_chat_member', (msg) => {
//     const chatId = msg.chat.id;
//     const leftMember = msg.left_chat_member;
    
//     if (leftMember.id === bot.getMe().then(me => me.id)) {
//         // 机器人被移除
//         console.log(`机器人被移除出群组: ${chatId}`);
//     } else {
//         // 其他成员离开
//         console.log(`成员离开群组: ${leftMember.username || leftMember.first_name} (${leftMember.id})`);
//         sendMessage(chatId, `${leftMember.username || leftMember.first_name} 离开了群组。`);
//     }
// });

// // 处理群组标题更改
// bot.on('new_chat_title', (msg) => {
//     console.log(`群组标题更改: ${msg.chat.title} (${msg.chat.id})`);
//     sendMessage(msg.chat.id, `群组标题已更改为: ${msg.chat.title}`);
// });

// // 处理群组照片更改
// bot.on('new_chat_photo', (msg) => {
//     console.log(`群组照片更改: ${msg.chat.id}`);
//     sendMessage(msg.chat.id, '群组照片已更新!');
// });

// // 处理消息删除
// bot.on('delete_chat_photo', (msg) => {
//     console.log(`群组照片被删除: ${msg.chat.id}`);
//     sendMessage(msg.chat.id, '群组照片已被删除。');
// });

// // 处理管理员命令
// bot.onText(/\/addgroup (.+)/, async (msg, match) => {
//     if (!isAdmin(msg.from.id)) {
//         sendMessage(msg.chat.id, '您没有权限执行此命令。');
//         return;
//     }

//     const groupId = match[1].trim();
//     if (!data.allowedGroups.includes(groupId)) {
//         try {
//             // 使用 createGroup 创建新群组
//             const groupData = {
//                 groupId: groupId,
//                 groupName: '手动添加的群组',
//                 groupType: 'public'
//             };
            
//             const result = await createGroup({ body: groupData });
//             if (result) {
//                 data.allowedGroups.push(groupId);
//                 saveData();
//                 sendMessage(msg.chat.id, `群组 ${groupId} 已添加到允许列表。`);
//             } else {
//                 sendMessage(msg.chat.id, '添加群组失败,请检查群组ID是否正确。');
//             }
//         } catch (error) {
//             console.error('创建群组失败:', error);
//             sendMessage(msg.chat.id, '添加群组失败,请稍后重试。');
//         }
//     } else {
//         sendMessage(msg.chat.id, '该群组已在允许列表中。');
//     }
// });

// bot.onText(/\/removegroup (.+)/, async (msg, match) => {
//     if (!isAdmin(msg.from.id)) {
//         sendMessage(msg.chat.id, '您没有权限执行此命令。');
//         return;
//     }

//     const groupId = match[1].trim();
//     try {
//         // 使用 updateGroup 更新群组状态
//         const result = await updateGroup({ 
//             params: { id: groupId },
//             body: { isActive: false }
//         });
        
//         if (result) {
//             const index = data.allowedGroups.indexOf(groupId);
//             if (index > -1) {
//                 data.allowedGroups.splice(index, 1);
//                 saveData();
//                 sendMessage(msg.chat.id, `群组 ${groupId} 已从允许列表中移除。`);
//             } else {
//                 sendMessage(msg.chat.id, '该群组不在允许列表中。');
//             }
//         } else {
//             sendMessage(msg.chat.id, '移除群组失败,请稍后重试。');
//         }
//     } catch (error) {
//         console.error('更新群组状态失败:', error);
//         sendMessage(msg.chat.id, '移除群组失败,请稍后重试。');
//     }
// });

// bot.onText(/\/listgroups/, (msg) => {
//     if (!isAdmin(msg.from.id)) {
//         sendMessage(msg.chat.id, '您没有权限执行此命令。');
//         return;
//     }

//     const groupsList = data.allowedGroups.join('\n');
//     sendMessage(msg.chat.id, `允许的群组列表:\n${groupsList}`);
// });

// // 处理所有消息
// bot.on('message', (msg) => {
//     console.log('收到消息:', {
//         chatId: msg.chat.id,
//         chatType: msg.chat.type,
//         chatTitle: msg.chat.title,
//         fromId: msg.from.id,
//         fromUsername: msg.from.username,
//         text: msg.text,
//         date: new Date(msg.date * 1000).toLocaleString()
//     });
// });

// // 处理错误
// bot.on('polling_error', (error) => {
//     console.error('轮询错误:', error);
//     if (error.message.includes('bot was kicked from the group chat')) {
//         const chatId = error.message.match(/chat (\d+)/)?.[1];
//         if (chatId) {
//             // 从允许列表中移除被踢出的群组
//             const index = data.allowedGroups.indexOf(chatId);
//             if (index > -1) {
//                 data.allowedGroups.splice(index, 1);
//                 saveData();
//                 console.log(`群组 ${chatId} 已被移除出允许列表`);
//             }
//         }
//     }
// });

// bot.on('webhook_error', (error) => {
//     console.error('Webhook错误:', error);
// });

// // 处理消息发送错误
// bot.on('error', (error) => {
//     console.error('机器人错误:', error);
//     if (error.message.includes('bot was kicked from the group chat')) {
//         const chatId = error.message.match(/chat (\d+)/)?.[1];
//         if (chatId) {
//             // 从允许列表中移除被踢出的群组
//             const index = data.allowedGroups.indexOf(chatId);
//             if (index > -1) {
//                 data.allowedGroups.splice(index, 1);
//                 saveData();
//                 console.log(`群组 ${chatId} 已被移除出允许列表`);
//             }
//         }
//     }
// });

// // 处理消息发送
// async function sendMessage(chatId, text, options = {}) {
//     try {
//         return await bot.sendMessage(chatId, text, options);
//     } catch (error) {
//         console.error('发送消息失败:', error);
//         if (error.message.includes('bot was kicked from the group chat')) {
//             const index = data.allowedGroups.indexOf(chatId.toString());
//             if (index > -1) {
//                 data.allowedGroups.splice(index, 1);
//                 saveData();
//                 console.log(`群组 ${chatId} 已被移除出允许列表`);
//             }
//         }
//         return null;
//     }
// }

// // 生成账单消息
// function generateBillMessage() {
//     const now = moment();
//     const deposits = data.deposits || [];
//     const withdrawals = data.withdrawals || [];
    
//     const totalDeposit = deposits.reduce((sum, d) => sum + d.amount, 0);
//     const totalWithdrawal = withdrawals.reduce((sum, w) => sum + w.amount, 0);
//     const depositFee = totalDeposit * config.DEPOSIT_FEE_RATE;
//     const withdrawalFee = totalWithdrawal * config.WITHDRAWAL_FEE_RATE;
//     const remaining = totalDeposit - depositFee - totalWithdrawal - withdrawalFee;

//     let message = `入款(${deposits.length})笔:\n`;
    
//     // 添加入款记录
//     deposits.forEach(deposit => {
//         message += `${moment(deposit.time).format('HH:mm:ss')} ${deposit.amount.toFixed(2)}\n`;
//     });

//     message += `\n下发(${withdrawals.length})笔:\n`;
    
//     // 添加下发记录
//     withdrawals.forEach(withdrawal => {
//         message += `${moment(withdrawal.time).format('HH:mm:ss')} ${withdrawal.amount.toFixed(2)}\n`;
//     });

//     message += `\n总入款:${totalDeposit.toFixed(2)}\n`;
//     message += `入款费率:${(config.DEPOSIT_FEE_RATE * 100).toFixed(1)}%\n`;
//     message += `下发费率:${(config.WITHDRAWAL_FEE_RATE * 100).toFixed(1)}%\n`;
//     message += `应下发:${(totalDeposit - depositFee).toFixed(2)}\n`;
//     message += `总下发:${totalWithdrawal.toFixed(2)}\n`;
//     message += `下发单笔附加费:0.0\n`;
//     message += `单笔附费加总计:0.0\n`;
//     message += `余:${remaining.toFixed(2)}`;

//     return message;
// }

// // 生成内联键盘
// function generateInlineKeyboard() {
//     return {
//         inline_keyboard: [
//             [
//                 {
//                     text: '点击跳转完整账单',
//                     url: `${config.BILL_PAGE_BASE_URL}?groupId=${data.allowedGroups[0]}`
//                 }
//             ],
//             [
//                 {
//                     text: '24小时商务对接',
//                     url: 'https://t.me/your_business_account' // 请替换为实际的商务账号
//                 }
//             ]
//         ]
//     };
// }

// // 处理入款命令
// bot.onText(/\/deposit (.+)/, (msg, match) => {
//     // if (!isGroupAllowed(msg.chat.id)) {
//     //     bot.sendMessage(msg.chat.id, '此群组未授权使用此机器人');
//     //     return;
//     // }

//     const amount = parseFloat(match[1]);
//     if (isNaN(amount)) {
//         sendMessage(msg.chat.id, '请输入有效的金额');
//         return;
//     }

//     data.deposits.push({
//         time: new Date(),
//         amount: amount
//     });
//     data.lastUpdate = new Date();
//     saveData();

//     sendMessage(msg.chat.id, generateBillMessage(), {
//         reply_markup: generateInlineKeyboard()
//     });
// });

// // 处理下发命令
// bot.onText(/\/withdraw (.+)/, (msg, match) => {
//     // if (!isGroupAllowed(msg.chat.id)) {
//     //     bot.sendMessage(msg.chat.id, '此群组未授权使用此机器人');
//     //     return;
//     // }

//     const amount = parseFloat(match[1]);
//     if (isNaN(amount)) {
//         sendMessage(msg.chat.id, '请输入有效的金额');
//         return;
//     }

//     data.withdrawals.push({
//         time: new Date(),
//         amount: amount
//     });
//     data.lastUpdate = new Date();
//     saveData();

//     sendMessage(msg.chat.id, generateBillMessage(), {
//         reply_markup: generateInlineKeyboard()
//     });
// });

// // 处理查看账单命令
// bot.onText(/\/bill/, (msg) => {
//     // if (!isGroupAllowed(msg.chat.id)) {
//     //     bot.sendMessage(msg.chat.id, '此群组未授权使用此机器人');
//     //     return;
//     // }
//     sendMessage(msg.chat.id, generateBillMessage(), {
//         reply_markup: generateInlineKeyboard()
//     });
// });

// // 更新帮助命令
// bot.onText(/\/help/, (msg) => {
//     const helpMessage = `
// 可用命令:
// /deposit <金额> - 记录入款
// /withdraw <金额> - 记录下发
// /bill - 查看当前账单
// /help - 显示此帮助信息

// 管理员命令:
// /addgroup <群组ID> - 添加允许的群组
// /removegroup <群组ID> - 移除允许的群组
// /listgroups - 列出所有允许的群组
//     `;
//     sendMessage(msg.chat.id, helpMessage);
// });

// // 启动Express服务器
// app.listen(8080, () => {
//     console.log(`Server is running on port 8080`);
//     loadData();
//     console.log('Bot is ready to use!');
// });