/**
 * 添加"职位类型管理"菜单项到系统设置菜单下
 * 执行 SQL 插入操作
 */

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

async function addJobTypesMenu() {
    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;

        // 先查找系统设置菜单的ID（通常 parent_id 为 0 或特定的系统菜单ID）
        // 需要根据实际情况调整查询条件
        const [systemMenu] = await sequelize.query(
            `SELECT id FROM sys_menu WHERE (name LIKE '%系统%' OR name LIKE '%设置%') AND parent_id = 0 AND is_delete = 0 LIMIT 1`,
            { type: Sequelize.QueryTypes.SELECT }
        );

        let parentId = 0;
        if (systemMenu && systemMenu.id) {
            parentId = systemMenu.id;
            console.log(`找到系统设置菜单，ID: ${parentId}`);
        } else {
            // 如果没有找到，尝试查找 system_config 菜单的父菜单
            const [configMenu] = await sequelize.query(
                `SELECT parent_id FROM sys_menu WHERE path = 'system_config' AND is_delete = 0 LIMIT 1`,
                { type: Sequelize.QueryTypes.SELECT }
            );
            if (configMenu && configMenu.parent_id) {
                parentId = configMenu.parent_id;
                console.log(`从系统配置菜单获取父菜单ID: ${parentId}`);
            } else {
                console.log('未找到系统设置菜单，将使用 parent_id = 0');
            }
        }

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

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

        // 获取最大排序值
        const [maxSort] = await sequelize.query(
            `SELECT MAX(sort) as maxSort FROM sys_menu WHERE parent_id = ${parentId} AND is_delete = 0`,
            { type: Sequelize.QueryTypes.SELECT }
        );
        const nextSort = (maxSort && maxSort.maxSort ? maxSort.maxSort : 0) + 1;

        // 执行插入
        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 (
                '职位类型管理',
                ${parentId},
                0,
                0,
                'md-briefcase',
                'job_types',
                'system/job_types.vue',
                'system/job_types_server.js',
                1,
                1,
                '页面',
                ${nextSort},
                NOW(),
                NOW(),
                0
            )`,
            { type: Sequelize.QueryTypes.INSERT }
        );

        console.log('✅ "职位类型管理"菜单项添加成功！\n');

        // 验证插入结果
        const [menu] = await sequelize.query(
            `SELECT id, name, parent_id, path, component, api_path, sort 
             FROM sys_menu 
             WHERE path = 'job_types' AND is_delete = 0`,
            { type: Sequelize.QueryTypes.SELECT }
        );
        
        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`);
        }

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

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

