/**
 * 更新菜单数据以匹配前端路由
 * @file update-menu-to-match-routes.js
 * @description 根据前端routes.js更新后端菜单数据
 */

const { MenuPermission } = require('../models');

async function updateMenuToMatchRoutes() {
  try {
    console.log('开始更新菜单数据以匹配前端路由...');

    // 清空现有菜单数据
    await MenuPermission.destroy({ where: {} });
    console.log('已清空现有菜单数据');

    // 根据前端routes.js定义菜单数据
    const menuData = [
      // 系统概览
      {
        menu_key: 'dashboard',
        menu_name: '系统概览',
        menu_path: '/dashboard',
        parent_id: null,
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'dashboard-outlined',
        sort_order: 1,
        is_visible: true,
        is_enabled: true,
        description: '系统概览和统计信息'
      },

      // 智能设备管理
      {
        menu_key: 'smart_device.main',
        menu_name: '智能设备',
        menu_path: '/smart-devices',
        parent_id: null,
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'SettingOutlined',
        sort_order: 2,
        is_visible: true,
        is_enabled: true,
        description: '智能设备管理',
        permission: 'smart_device:view'
      },
      {
        menu_key: 'smart_device.eartag',
        menu_name: '智能耳标',
        menu_path: '/smart-devices/eartag',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 1,
        is_visible: true,
        is_enabled: true,
        description: '智能耳标管理',
        permission: 'smart_eartag:view'
      },
      {
        menu_key: 'smart_device.collar',
        menu_name: '智能项圈',
        menu_path: '/smart-devices/collar',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 2,
        is_visible: true,
        is_enabled: true,
        description: '智能项圈管理',
        permission: 'smart_collar:view'
      },
      {
        menu_key: 'smart_device.host',
        menu_name: '智能主机',
        menu_path: '/smart-devices/host',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 3,
        is_visible: true,
        is_enabled: true,
        description: '智能主机管理',
        permission: 'smart_host:view'
      },
      {
        menu_key: 'smart_device.fence',
        menu_name: '电子围栏',
        menu_path: '/smart-devices/fence',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 4,
        is_visible: true,
        is_enabled: true,
        description: '电子围栏管理',
        permission: 'smart_fence:view'
      },

      // 智能预警管理
      {
        menu_key: 'smart_alert.main',
        menu_name: '智能预警总览',
        menu_path: '/smart-alerts',
        parent_id: null,
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'AlertOutlined',
        sort_order: 3,
        is_visible: true,
        is_enabled: true,
        description: '智能预警管理',
        permission: 'smart_alert:view'
      },
      {
        menu_key: 'smart_alert.eartag',
        menu_name: '智能耳标预警',
        menu_path: '/smart-alerts/eartag',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 1,
        is_visible: true,
        is_enabled: true,
        description: '智能耳标预警管理',
        permission: 'smart_eartag_alert:view'
      },
      {
        menu_key: 'smart_alert.collar',
        menu_name: '智能项圈预警',
        menu_path: '/smart-alerts/collar',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 2,
        is_visible: true,
        is_enabled: true,
        description: '智能项圈预警管理',
        permission: 'smart_collar_alert:view'
      },

      // 牛只管理
      {
        menu_key: 'animal.management',
        menu_name: '牛只管理',
        menu_path: '/cattle-management',
        parent_id: null,
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'BugOutlined',
        sort_order: 4,
        is_visible: true,
        is_enabled: true,
        description: '牛只管理',
        permission: 'animal:view'
      },
      {
        menu_key: 'cattle.archives',
        menu_name: '牛只档案',
        menu_path: '/cattle-management/archives',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 1,
        is_visible: true,
        is_enabled: true,
        description: '牛只档案管理',
        permission: 'cattle:archives:view'
      },
      {
        menu_key: 'cattle.pens',
        menu_name: '栏舍设置',
        menu_path: '/cattle-management/pens',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 2,
        is_visible: true,
        is_enabled: true,
        description: '栏舍设置管理',
        permission: 'cattle:pens:view'
      },
      {
        menu_key: 'cattle.batches',
        menu_name: '批次设置',
        menu_path: '/cattle-management/batches',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 3,
        is_visible: true,
        is_enabled: true,
        description: '批次设置管理',
        permission: 'cattle:batches:view'
      },
      {
        menu_key: 'cattle.transfer',
        menu_name: '转栏记录',
        menu_path: '/cattle-management/transfer-records',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 4,
        is_visible: true,
        is_enabled: true,
        description: '转栏记录管理',
        permission: 'cattle:transfer:view'
      },
      {
        menu_key: 'cattle.exit',
        menu_name: '离栏记录',
        menu_path: '/cattle-management/exit-records',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager", "operator"]',
        icon: 'FileOutlined',
        sort_order: 5,
        is_visible: true,
        is_enabled: true,
        description: '离栏记录管理',
        permission: 'cattle:exit:view'
      },

      // 养殖场管理
      {
        menu_key: 'farm.main',
        menu_name: '养殖场管理',
        menu_path: '/farm-management',
        parent_id: null,
        menu_type: 'page',
        required_roles: '["admin", "manager"]',
        icon: 'HomeOutlined',
        sort_order: 5,
        is_visible: true,
        is_enabled: true,
        description: '养殖场管理',
        permission: 'farm:view'
      },
      {
        menu_key: 'farm.info',
        menu_name: '养殖场信息管理',
        menu_path: '/farm-management/info',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager"]',
        icon: 'FileOutlined',
        sort_order: 1,
        is_visible: true,
        is_enabled: true,
        description: '养殖场信息管理',
        permission: 'farm_info:view'
      },
      {
        menu_key: 'farm.pens',
        menu_name: '栏舍管理',
        menu_path: '/farm-management/pens',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin", "manager"]',
        icon: 'FileOutlined',
        sort_order: 2,
        is_visible: true,
        is_enabled: true,
        description: '栏舍管理',
        permission: 'pen:view'
      },
      {
        menu_key: 'farm.users',
        menu_name: '用户管理',
        menu_path: '/farm-management/users',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin"]',
        icon: 'FileOutlined',
        sort_order: 3,
        is_visible: true,
        is_enabled: true,
        description: '用户管理',
        permission: 'user:view'
      },
      {
        menu_key: 'farm.role_permissions',
        menu_name: '角色权限管理',
        menu_path: '/farm-management/role-permissions',
        parent_id: null, // 将在后面更新
        menu_type: 'page',
        required_roles: '["admin"]',
        icon: 'SafetyCertificateOutlined',
        sort_order: 4,
        is_visible: true,
        is_enabled: true,
        description: '角色权限管理',
        permission: 'role:view'
      },

      // 系统管理
      {
        menu_key: 'system.config',
        menu_name: '系统管理',
        menu_path: '/system',
        parent_id: null,
        menu_type: 'page',
        required_roles: '["admin"]',
        icon: 'setting-outlined',
        sort_order: 6,
        is_visible: true,
        is_enabled: true,
        description: '系统管理',
        permission: 'system:config'
      }
    ];

    // 创建菜单
    const createdMenus = [];
    for (const menuDataItem of menuData) {
      try {
        const menu = await MenuPermission.create(menuDataItem);
        createdMenus.push(menu);
        console.log(`创建菜单: ${menu.menu_name} (ID: ${menu.id})`);
      } catch (error) {
        console.error(`创建菜单失败 ${menuDataItem.menu_name}:`, error.message);
      }
    }

    // 更新子菜单的parent_id
    const menuMap = new Map();
    createdMenus.forEach(menu => {
      menuMap.set(menu.menu_key, menu.id);
    });

    // 更新智能设备子菜单
    const smartDeviceMenus = [
      { key: 'smart_device.eartag', parent: 'smart_device.main' },
      { key: 'smart_device.collar', parent: 'smart_device.main' },
      { key: 'smart_device.host', parent: 'smart_device.main' },
      { key: 'smart_device.fence', parent: 'smart_device.main' }
    ];

    for (const menu of smartDeviceMenus) {
      const menuId = menuMap.get(menu.key);
      const parentId = menuMap.get(menu.parent);
      if (menuId && parentId) {
        await MenuPermission.update(
          { parent_id: parentId },
          { where: { id: menuId } }
        );
        console.log(`更新菜单关系: ${menu.key} -> ${menu.parent}`);
      }
    }

    // 更新智能预警子菜单
    const smartAlertMenus = [
      { key: 'smart_alert.eartag', parent: 'smart_alert.main' },
      { key: 'smart_alert.collar', parent: 'smart_alert.main' }
    ];

    for (const menu of smartAlertMenus) {
      const menuId = menuMap.get(menu.key);
      const parentId = menuMap.get(menu.parent);
      if (menuId && parentId) {
        await MenuPermission.update(
          { parent_id: parentId },
          { where: { id: menuId } }
        );
        console.log(`更新菜单关系: ${menu.key} -> ${menu.parent}`);
      }
    }

    // 更新牛只管理子菜单
    const cattleMenus = [
      { key: 'cattle.archives', parent: 'animal.management' },
      { key: 'cattle.pens', parent: 'animal.management' },
      { key: 'cattle.batches', parent: 'animal.management' },
      { key: 'cattle.transfer', parent: 'animal.management' },
      { key: 'cattle.exit', parent: 'animal.management' }
    ];

    for (const menu of cattleMenus) {
      const menuId = menuMap.get(menu.key);
      const parentId = menuMap.get(menu.parent);
      if (menuId && parentId) {
        await MenuPermission.update(
          { parent_id: parentId },
          { where: { id: menuId } }
        );
        console.log(`更新菜单关系: ${menu.key} -> ${menu.parent}`);
      }
    }

    // 更新养殖场管理子菜单
    const farmMenus = [
      { key: 'farm.info', parent: 'farm.main' },
      { key: 'farm.pens', parent: 'farm.main' },
      { key: 'farm.users', parent: 'farm.main' },
      { key: 'farm.role_permissions', parent: 'farm.main' }
    ];

    for (const menu of farmMenus) {
      const menuId = menuMap.get(menu.key);
      const parentId = menuMap.get(menu.parent);
      if (menuId && parentId) {
        await MenuPermission.update(
          { parent_id: parentId },
          { where: { id: menuId } }
        );
        console.log(`更新菜单关系: ${menu.key} -> ${menu.parent}`);
      }
    }

    console.log('菜单数据更新完成！');
    console.log(`共创建了 ${createdMenus.length} 个菜单项`);

  } catch (error) {
    console.error('更新菜单数据失败:', error);
  } finally {
    process.exit(0);
  }
}

// 运行脚本
updateMenuToMatchRoutes();
