// 初始化菜单表结构并插入数据
const { sequelize } = require('../config/database');
const { DataTypes } = require('sequelize');

// 定义Menu模型
const Menu = sequelize.define('Menu', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: DataTypes.STRING(50),
    allowNull: false,
    validate: {
      len: [2, 50]
    }
  },
  key: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    validate: {
      len: [2, 50]
    }
  },
  path: {
    type: DataTypes.STRING(100),
    allowNull: false,
    validate: {
      len: [1, 100]
    }
  },
  icon: {
    type: DataTypes.STRING(50),
    allowNull: true
  },
  parent_id: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: 'menus',
      key: 'id'
    },
    defaultValue: null
  },
  component: {
    type: DataTypes.STRING(100),
    allowNull: true
  },
  order: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive'),
    defaultValue: 'active'
  },
  show: {
    type: DataTypes.BOOLEAN,
    defaultValue: true
  }
}, {
  tableName: 'menus',
  timestamps: true,
  underscored: true,
  indexes: [
    { fields: ['key'] },
    { fields: ['parent_id'] },
    { fields: ['status'] },
    { fields: ['order'] }
  ]
});

// 设置自关联
Menu.hasMany(Menu, {
  as: 'children',
  foreignKey: 'parent_id'
});

Menu.belongsTo(Menu, {
  as: 'parent',
  foreignKey: 'parent_id'
});

// 初始化函数
async function initializeMenus() {
  try {
    console.log('🔄 开始初始化菜单表结构...');
    
    // 检查并创建表
    const tableExists = await sequelize.query(
      "SHOW TABLES LIKE 'menus'"
    );
    
    if (tableExists[0].length === 0) {
      console.log('📝 menus表不存在，开始创建...');
      await Menu.sync({ force: true });
      console.log('✅ menus表创建成功');
    } else {
      console.log('ℹ️ menus表已存在，开始清空数据...');
      await sequelize.query('SET FOREIGN_KEY_CHECKS = 0');
      await sequelize.query('TRUNCATE TABLE menus');
      await sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
      console.log('✅ menus表数据已清空');
    }
    
    console.log('📊 开始插入菜单数据...');
    
    // 插入父级菜单
    const parentMenus = await Menu.bulkCreate([
      { name: '仪表板', key: 'Dashboard', path: '/dashboard', icon: 'DashboardOutlined', parent_id: null, component: 'views/Dashboard.vue', order: 1, status: 'active', show: true },
      { name: '数据览仓', key: 'DataWarehouse', path: '/data-warehouse', icon: 'DatabaseOutlined', parent_id: null, component: '', order: 2, status: 'active', show: true },
      { name: '监管任务', key: 'SupervisionTask', path: '/supervision-task', icon: 'CheckCircleOutlined', parent_id: null, component: '', order: 3, status: 'active', show: true },
      { name: '待安装任务', key: 'PendingInstallationTask', path: '/pending-installation', icon: 'ExclamationCircleOutlined', parent_id: null, component: '', order: 4, status: 'active', show: true },
      { name: '监管任务已结项', key: 'CompletedTask', path: '/completed-tasks', icon: 'FileDoneOutlined', parent_id: null, component: '', order: 5, status: 'active', show: true },
      { name: '投保客户单', key: 'InsuredCustomers', path: '/insured-customers', icon: 'ShopOutlined', parent_id: null, component: '', order: 6, status: 'active', show: true },
      { name: '生资保单', key: 'AgriculturalInsurance', path: '/agricultural-insurance', icon: 'FileProtectOutlined', parent_id: null, component: '', order: 7, status: 'active', show: true },
      { name: '险种管理', key: 'InsuranceTypeManagement', path: '/insurance-types', icon: 'MedicineBoxOutlined', parent_id: null, component: '', order: 8, status: 'active', show: true },
      { name: '客户理赔', key: 'CustomerClaims', path: '/customer-claims', icon: 'AlertCircleOutlined', parent_id: null, component: '', order: 9, status: 'active', show: true },
      { name: '消息通知', key: 'Notifications', path: '/notifications', icon: 'BellOutlined', parent_id: null, component: '', order: 10, status: 'active', show: true },
      { name: '子账号管理', key: 'UserManagement', path: '/users', icon: 'UserAddOutlined', parent_id: null, component: 'views/UserManagement.vue', order: 11, status: 'active', show: true },
      { name: '系统设置', key: 'SystemSettings', path: '/system-settings', icon: 'SettingOutlined', parent_id: null, component: '', order: 12, status: 'active', show: true },
      { name: '个人中心', key: 'UserProfile', path: '/profile', icon: 'UserSwitchOutlined', parent_id: null, component: '', order: 13, status: 'active', show: true }
    ]);
    
    console.log(`✅ 已插入 ${parentMenus.length} 条父级菜单数据`);
    
    // 查找父级菜单ID
    const parentMenuMap = {};
    for (const menu of parentMenus) {
      parentMenuMap[menu.key] = menu.id;
    }
    
    // 插入子菜单
    const subMenus = await Menu.bulkCreate([
      // 投保客户单的子菜单
      { name: '参保申请', key: 'ApplicationManagement', path: '/applications', icon: 'FileTextOutlined', parent_id: parentMenuMap.InsuredCustomers, component: 'views/ApplicationManagement.vue', order: 1, status: 'active', show: true },
      
      // 生资保单的子菜单
      { name: '生资保单列表', key: 'PolicyManagement', path: '/policies', icon: 'FileDoneOutlined', parent_id: parentMenuMap.AgriculturalInsurance, component: 'views/PolicyManagement.vue', order: 1, status: 'active', show: true },
      
      // 险种管理的子菜单
      { name: '险种管理', key: 'InsuranceTypeList', path: '/insurance-types', icon: 'MedicineBoxOutlined', parent_id: parentMenuMap.InsuranceTypeManagement, component: 'views/InsuranceTypeManagement.vue', order: 1, status: 'active', show: true },
      
      // 客户理赔的子菜单
      { name: '客户理赔', key: 'ClaimManagement', path: '/claims', icon: 'SafetyCertificateOutlined', parent_id: parentMenuMap.CustomerClaims, component: 'views/ClaimManagement.vue', order: 1, status: 'active', show: true }
    ]);
    
    console.log(`✅ 已插入 ${subMenus.length} 条子菜单数据`);
    
    // 查询所有菜单
    const allMenus = await Menu.findAll({ 
      order: [['parent_id', 'ASC'], ['order', 'ASC']],
      include: [{ model: Menu, as: 'children' }]
    });
    
    console.log(`✅ 菜单数据初始化完成，共 ${allMenus.length} 条记录`);
    
  } catch (error) {
    console.error('❌ 菜单数据初始化失败:', error.message);
    throw error;
  } finally {
    // 关闭数据库连接
    await sequelize.close();
    console.log('🔌 数据库连接已关闭');
  }
}

// 执行初始化
initializeMenus().catch(err => {
  console.error('❌ 菜单数据初始化任务失败');
  process.exit(1);
});