/**
 * 添加"账号列表"菜单项到用户管理菜单下
 * 执行 SQL 插入操作
 */

const Framework = require('../framework/node-core-framework.js');
const frameworkConfig = require('../config/framework.config.js');

async function addAccountListMenu() {
    console.log('🔄 开始添加"账号列表"菜单项...\n');

    try {
        // 初始化框架
        console.log('正在初始化框架...');
        const framework = await Framework.init(frameworkConfig);
        const models = Framework.getModels();
        
        if (!models) {
            throw new Error('无法获取模型列表');
        }

        // 从任意模型获取 sequelize 实例
        const Sequelize = require('sequelize');
        const firstModel = Object.values(models)[0];
        if (!firstModel || !firstModel.sequelize) {
            throw new Error('无法获取数据库连接');
        }
        const sequelize = firstModel.sequelize;

        // 检查是否已存在
        const [existing] = await sequelize.query(
            `SELECT id, name FROM sys_menu WHERE parent_id = 120 AND path = 'pla_account' AND is_delete = 0`,
            { type: Sequelize.QueryTypes.SELECT }
        );

        if (existing) {
            console.log(`⚠️  菜单项已存在 (ID: ${existing.id}, 名称: ${existing.name})`);
            console.log('✅ 无需重复添加\n');
            return;
        }

        // 执行插入
        const [result] = await sequelize.query(
            `INSERT INTO sys_menu (
                name, 
                parent_id, 
                model_id, 
                form_id, 
                icon, 
                path, 
                component, 
                api_path, 
                is_show_menu, 
                is_show, 
                type, 
                sort, 
                create_time, 
                last_modify_time, 
                is_delete
            ) VALUES (
                '账号列表',
                120,
                0,
                0,
                'md-list',
                'pla_account',
                'account/pla_account.vue',
                'account/pla_account_server.js',
                1,
                1,
                '页面',
                1,
                NOW(),
                NOW(),
                0
            )`,
            { type: Sequelize.QueryTypes.INSERT }
        );

        console.log('✅ "账号列表"菜单项添加成功！\n');

        // 验证插入结果（通过 path 查询）
        const [menus] = await sequelize.query(
            `SELECT id, name, parent_id, path, component, api_path, sort 
             FROM sys_menu 
             WHERE parent_id = 120 AND path = 'pla_account' AND is_delete = 0`,
            { type: Sequelize.QueryTypes.SELECT }
        );
        
        const menu = menus && menus.length > 0 ? menus[0] : null;

        if (menu) {
            console.log('📋 菜单项详情：');
            console.log(`   名称: ${menu.name}`);
            console.log(`   父菜单ID: ${menu.parent_id}`);
            console.log(`   路由路径: ${menu.path}`);
            console.log(`   组件路径: ${menu.component}`);
            console.log(`   API路径: ${menu.api_path}`);
            console.log(`   排序: ${menu.sort}\n`);
        }

        // 显示用户管理菜单下的所有子菜单
        const [children] = await sequelize.query(
            `SELECT id, name, path, sort, is_show_menu 
             FROM sys_menu 
             WHERE parent_id = 120 AND is_delete = 0 
             ORDER BY sort`,
            { type: Sequelize.QueryTypes.SELECT }
        );

        console.log('📋 用户管理菜单下的所有子菜单：');
        children.forEach(child => {
            const visible = child.is_show_menu ? '✅' : '🔒';
            console.log(`   ${visible} ${child.name} (ID: ${child.id}, 路径: ${child.path}, 排序: ${child.sort})`);
        });

    } catch (error) {
        console.error('❌ 添加失败:', error.message);
        console.error('\n详细错误:', error);
        throw error;
    }
}

// 执行添加
addAccountListMenu()
    .then(() => {
        console.log('\n✨ 操作完成！');
        process.exit(0);
    })
    .catch(error => {
        console.error('\n💥 执行失败:', error);
        process.exit(1);
    });

