/**
 * 优化权限管理数据库结构
 * 创建permissions表，优化role_permissions表，实现完整的权限管理
 */

const { sequelize } = require('../config/database-simple');

async function optimizePermissionStructure() {
  try {
    console.log('开始优化权限管理数据库结构...');
    
    // 1. 创建permissions表
    console.log('1. 创建permissions表...');
    await sequelize.query(`
      CREATE TABLE IF NOT EXISTS permissions (
        id INT(11) NOT NULL AUTO_INCREMENT,
        permission_key VARCHAR(100) NOT NULL UNIQUE COMMENT '权限标识',
        permission_name VARCHAR(100) NOT NULL COMMENT '权限名称',
        permission_desc TEXT COMMENT '权限描述',
        module VARCHAR(50) NOT NULL COMMENT '所属模块',
        action VARCHAR(50) NOT NULL COMMENT '操作类型',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        INDEX idx_module (module),
        INDEX idx_action (action),
        INDEX idx_permission_key (permission_key)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='权限定义表'
    `);
    
    // 2. 优化role_permissions表结构
    console.log('2. 优化role_permissions表结构...');
    
    // 先备份现有数据
    const [existingData] = await sequelize.query('SELECT * FROM role_permissions');
    console.log(`备份了 ${existingData.length} 条现有数据`);
    
    // 删除现有表
    await sequelize.query('DROP TABLE IF EXISTS role_permissions');
    
    // 创建新的role_permissions表
    await sequelize.query(`
      CREATE TABLE role_permissions (
        id INT(11) NOT NULL AUTO_INCREMENT,
        role_id INT(11) NOT NULL COMMENT '角色ID',
        permission_id INT(11) NOT NULL COMMENT '权限ID',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY uk_role_permission (role_id, permission_id),
        INDEX idx_role_id (role_id),
        INDEX idx_permission_id (permission_id),
        FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
        FOREIGN KEY (permission_id) REFERENCES permissions(id) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='角色权限关联表'
    `);
    
    // 3. 插入权限数据
    console.log('3. 插入权限数据...');
    const permissions = [
      // 用户管理权限
      { key: 'user:view', name: '查看用户', desc: '查看用户列表和详情', module: 'user', action: 'view' },
      { key: 'user:create', name: '创建用户', desc: '创建新用户', module: 'user', action: 'create' },
      { key: 'user:update', name: '更新用户', desc: '更新用户信息', module: 'user', action: 'update' },
      { key: 'user:delete', name: '删除用户', desc: '删除用户', module: 'user', action: 'delete' },
      
      // 角色管理权限
      { key: 'role:view', name: '查看角色', desc: '查看角色列表和详情', module: 'role', action: 'view' },
      { key: 'role:create', name: '创建角色', desc: '创建新角色', module: 'role', action: 'create' },
      { key: 'role:update', name: '更新角色', desc: '更新角色信息', module: 'role', action: 'update' },
      { key: 'role:delete', name: '删除角色', desc: '删除角色', module: 'role', action: 'delete' },
      { key: 'role:assign', name: '分配权限', desc: '为角色分配权限', module: 'role', action: 'assign' },
      
      // 养殖场管理权限
      { key: 'farm:view', name: '查看养殖场', desc: '查看养殖场列表和详情', module: 'farm', action: 'view' },
      { key: 'farm:create', name: '创建养殖场', desc: '创建新养殖场', module: 'farm', action: 'create' },
      { key: 'farm:update', name: '更新养殖场', desc: '更新养殖场信息', module: 'farm', action: 'update' },
      { key: 'farm:delete', name: '删除养殖场', desc: '删除养殖场', module: 'farm', action: 'delete' },
      
      // 设备管理权限
      { key: 'device:view', name: '查看设备', desc: '查看设备列表和详情', module: 'device', action: 'view' },
      { key: 'device:create', name: '创建设备', desc: '创建新设备', module: 'device', action: 'create' },
      { key: 'device:update', name: '更新设备', desc: '更新设备信息', module: 'device', action: 'update' },
      { key: 'device:delete', name: '删除设备', desc: '删除设备', module: 'device', action: 'delete' },
      { key: 'device:control', name: '控制设备', desc: '控制设备操作', module: 'device', action: 'control' },
      
      // 智能设备权限
      { key: 'smart_device:view', name: '查看智能设备', desc: '查看智能设备列表', module: 'smart_device', action: 'view' },
      { key: 'smart_device:manage', name: '管理智能设备', desc: '管理智能设备', module: 'smart_device', action: 'manage' },
      
      // 智能耳标权限
      { key: 'smart_eartag:view', name: '查看智能耳标', desc: '查看智能耳标列表', module: 'smart_eartag', action: 'view' },
      { key: 'smart_eartag:create', name: '创建智能耳标', desc: '创建智能耳标', module: 'smart_eartag', action: 'create' },
      { key: 'smart_eartag:update', name: '更新智能耳标', desc: '更新智能耳标信息', module: 'smart_eartag', action: 'update' },
      { key: 'smart_eartag:delete', name: '删除智能耳标', desc: '删除智能耳标', module: 'smart_eartag', action: 'delete' },
      
      // 智能脚环权限
      { key: 'smart_anklet:view', name: '查看智能脚环', desc: '查看智能脚环列表', module: 'smart_anklet', action: 'view' },
      { key: 'smart_anklet:create', name: '创建智能脚环', desc: '创建智能脚环', module: 'smart_anklet', action: 'create' },
      { key: 'smart_anklet:update', name: '更新智能脚环', desc: '更新智能脚环信息', module: 'smart_anklet', action: 'update' },
      { key: 'smart_anklet:delete', name: '删除智能脚环', desc: '删除智能脚环', module: 'smart_anklet', action: 'delete' },
      
      // 智能项圈权限
      { key: 'smart_collar:view', name: '查看智能项圈', desc: '查看智能项圈列表', module: 'smart_collar', action: 'view' },
      { key: 'smart_collar:create', name: '创建智能项圈', desc: '创建智能项圈', module: 'smart_collar', action: 'create' },
      { key: 'smart_collar:update', name: '更新智能项圈', desc: '更新智能项圈信息', module: 'smart_collar', action: 'update' },
      { key: 'smart_collar:delete', name: '删除智能项圈', desc: '删除智能项圈', module: 'smart_collar', action: 'delete' },
      
      // 智能主机权限
      { key: 'smart_host:view', name: '查看智能主机', desc: '查看智能主机列表', module: 'smart_host', action: 'view' },
      { key: 'smart_host:create', name: '创建智能主机', desc: '创建智能主机', module: 'smart_host', action: 'create' },
      { key: 'smart_host:update', name: '更新智能主机', desc: '更新智能主机信息', module: 'smart_host', action: 'update' },
      { key: 'smart_host:delete', name: '删除智能主机', desc: '删除智能主机', module: 'smart_host', action: 'delete' },
      
      // 智能围栏权限
      { key: 'smart_fence:view', name: '查看智能围栏', desc: '查看智能围栏列表', module: 'smart_fence', action: 'view' },
      { key: 'smart_fence:create', name: '创建智能围栏', desc: '创建智能围栏', module: 'smart_fence', action: 'create' },
      { key: 'smart_fence:update', name: '更新智能围栏', desc: '更新智能围栏信息', module: 'smart_fence', action: 'update' },
      { key: 'smart_fence:delete', name: '删除智能围栏', desc: '删除智能围栏', module: 'smart_fence', action: 'delete' },
      
      // 动物管理权限
      { key: 'animal:view', name: '查看动物', desc: '查看动物列表和详情', module: 'animal', action: 'view' },
      { key: 'animal:create', name: '创建动物', desc: '创建新动物', module: 'animal', action: 'create' },
      { key: 'animal:update', name: '更新动物', desc: '更新动物信息', module: 'animal', action: 'update' },
      { key: 'animal:delete', name: '删除动物', desc: '删除动物', module: 'animal', action: 'delete' },
      
      // 牛只管理权限
      { key: 'cattle:archives:view', name: '查看牛只档案', desc: '查看牛只档案列表', module: 'cattle', action: 'archives:view' },
      { key: 'cattle:archives:create', name: '创建牛只档案', desc: '创建牛只档案', module: 'cattle', action: 'archives:create' },
      { key: 'cattle:archives:update', name: '更新牛只档案', desc: '更新牛只档案信息', module: 'cattle', action: 'archives:update' },
      { key: 'cattle:archives:delete', name: '删除牛只档案', desc: '删除牛只档案', module: 'cattle', action: 'archives:delete' },
      
      { key: 'cattle:pens:view', name: '查看栏舍', desc: '查看栏舍列表', module: 'cattle', action: 'pens:view' },
      { key: 'cattle:pens:create', name: '创建栏舍', desc: '创建栏舍', module: 'cattle', action: 'pens:create' },
      { key: 'cattle:pens:update', name: '更新栏舍', desc: '更新栏舍信息', module: 'cattle', action: 'pens:update' },
      { key: 'cattle:pens:delete', name: '删除栏舍', desc: '删除栏舍', module: 'cattle', action: 'pens:delete' },
      
      // 预警管理权限
      { key: 'alert:view', name: '查看预警', desc: '查看预警列表', module: 'alert', action: 'view' },
      { key: 'alert:create', name: '创建预警', desc: '创建预警', module: 'alert', action: 'create' },
      { key: 'alert:update', name: '更新预警', desc: '更新预警信息', module: 'alert', action: 'update' },
      { key: 'alert:delete', name: '删除预警', desc: '删除预警', module: 'alert', action: 'delete' },
      { key: 'alert:handle', name: '处理预警', desc: '处理预警', module: 'alert', action: 'handle' },
      
      // 智能预警权限
      { key: 'smart_alert:view', name: '查看智能预警', desc: '查看智能预警列表', module: 'smart_alert', action: 'view' },
      { key: 'smart_eartag_alert:view', name: '查看耳标预警', desc: '查看耳标预警', module: 'smart_alert', action: 'eartag:view' },
      { key: 'smart_collar_alert:view', name: '查看项圈预警', desc: '查看项圈预警', module: 'smart_alert', action: 'collar:view' },
      
      // 数据分析权限
      { key: 'analytics:view', name: '查看分析', desc: '查看数据分析', module: 'analytics', action: 'view' },
      { key: 'report:generate', name: '生成报表', desc: '生成报表', module: 'report', action: 'generate' },
      { key: 'report:export', name: '导出报表', desc: '导出报表', module: 'report', action: 'export' },
      
      // 系统管理权限
      { key: 'system:config', name: '系统配置', desc: '系统配置管理', module: 'system', action: 'config' },
      { key: 'system:monitor', name: '系统监控', desc: '系统监控', module: 'system', action: 'monitor' },
      { key: 'system:backup', name: '系统备份', desc: '系统备份', module: 'system', action: 'backup' },
      
      // 实时监控权限
      { key: 'monitor:view', name: '实时监控', desc: '实时监控查看', module: 'monitor', action: 'view' },
      
      // 地图权限
      { key: 'map:view', name: '查看地图', desc: '查看地图', module: 'map', action: 'view' },
      { key: 'map:edit', name: '编辑地图', desc: '编辑地图标记', module: 'map', action: 'edit' },
      
      // 产品订单权限
      { key: 'product:view', name: '查看产品', desc: '查看产品列表', module: 'product', action: 'view' },
      { key: 'product:manage', name: '管理产品', desc: '管理产品', module: 'product', action: 'manage' },
      { key: 'order:view', name: '查看订单', desc: '查看订单列表', module: 'order', action: 'view' },
      { key: 'order:manage', name: '管理订单', desc: '管理订单', module: 'order', action: 'manage' }
    ];
    
    // 插入权限数据
    for (const permission of permissions) {
      await sequelize.query(`
        INSERT INTO permissions (permission_key, permission_name, permission_desc, module, action)
        VALUES ('${permission.key}', '${permission.name}', '${permission.desc}', '${permission.module}', '${permission.action}')
        ON DUPLICATE KEY UPDATE
        permission_name = VALUES(permission_name),
        permission_desc = VALUES(permission_desc),
        module = VALUES(module),
        action = VALUES(action)
      `);
    }
    
    console.log(`插入了 ${permissions.length} 个权限定义`);
    
    // 4. 为现有角色分配权限
    console.log('4. 为现有角色分配权限...');
    
    // 获取所有角色
    const [roles] = await sequelize.query('SELECT id, name FROM roles');
    console.log(`找到 ${roles.length} 个角色:`, roles.map(r => r.name));
    
    // 获取所有权限
    const [allPermissions] = await sequelize.query('SELECT id, permission_key FROM permissions');
    const permissionMap = new Map(allPermissions.map(p => [p.permission_key, p.id]));
    
    // 为admin角色分配所有权限
    const adminRole = roles.find(r => r.name === 'admin');
    if (adminRole) {
      console.log(`为admin角色分配所有权限...`);
      for (const permission of allPermissions) {
        await sequelize.query(`
          INSERT IGNORE INTO role_permissions (role_id, permission_id)
          VALUES (${adminRole.id}, ${permission.id})
        `);
      }
      console.log(`admin角色已分配 ${allPermissions.length} 个权限`);
    }
    
    // 为manager角色分配部分权限
    const managerRole = roles.find(r => r.name === 'manager');
    if (managerRole) {
      console.log(`为manager角色分配权限...`);
      const managerPermissions = [
        'user:view', 'farm:view', 'farm:create', 'farm:update',
        'device:view', 'device:create', 'device:update',
        'animal:view', 'animal:create', 'animal:update',
        'alert:view', 'alert:handle', 'analytics:view',
        'monitor:view', 'map:view', 'product:view', 'order:view'
      ];
      
      for (const permKey of managerPermissions) {
        const permId = permissionMap.get(permKey);
        if (permId) {
          await sequelize.query(`
            INSERT IGNORE INTO role_permissions (role_id, permission_id)
            VALUES (${managerRole.id}, ${permId})
          `);
        }
      }
      console.log(`manager角色已分配 ${managerPermissions.length} 个权限`);
    }
    
    // 为operator角色分配基础权限
    const operatorRole = roles.find(r => r.name === 'operator');
    if (operatorRole) {
      console.log(`为operator角色分配权限...`);
      const operatorPermissions = [
        'farm:view', 'device:view', 'animal:view',
        'alert:view', 'monitor:view', 'map:view'
      ];
      
      for (const permKey of operatorPermissions) {
        const permId = permissionMap.get(permKey);
        if (permId) {
          await sequelize.query(`
            INSERT IGNORE INTO role_permissions (role_id, permission_id)
            VALUES (${operatorRole.id}, ${permId})
          `);
        }
      }
      console.log(`operator角色已分配 ${operatorPermissions.length} 个权限`);
    }
    
    console.log('✅ 权限管理数据库结构优化完成！');
    console.log(`- 创建了permissions表，包含 ${permissions.length} 个权限定义`);
    console.log(`- 优化了role_permissions表结构`);
    console.log(`- 为现有角色分配了相应权限`);
    
  } catch (error) {
    console.error('❌ 优化权限管理数据库结构失败:', error);
    throw error;
  } finally {
    process.exit(0);
  }
}

optimizePermissionStructure();
