const { Permission, Role, RolePermission } = require('../models');
const { Op } = require('sequelize');

// 需要添加的权限列表
const missingPermissions = [
  // 用户管理权限
  { code: 'user:read', name: '用户查看', description: '查看用户信息', module: 'user', type: 'operation' },
  { code: 'user:create', name: '用户创建', description: '创建新用户', module: 'user', type: 'operation' },
  { code: 'user:update', name: '用户更新', description: '更新用户信息', module: 'user', type: 'operation' },
  { code: 'user:delete', name: '用户删除', description: '删除用户', module: 'user', type: 'operation' },

  // 保单管理权限
  { code: 'insurance:policy:create', name: '保单创建', description: '创建保单', module: 'insurance', type: 'operation' },
  { code: 'insurance:policy:edit', name: '保单编辑', description: '编辑保单信息', module: 'insurance', type: 'operation' },
  { code: 'insurance:policy:delete', name: '保单删除', description: '删除保单', module: 'insurance', type: 'operation' },

  // 保险申请权限
  { code: 'insurance:read', name: '保险申请查看', description: '查看保险申请', module: 'insurance', type: 'operation' },
  { code: 'insurance:create', name: '保险申请创建', description: '创建保险申请', module: 'insurance', type: 'operation' },
  { code: 'insurance:update', name: '保险申请更新', description: '更新保险申请', module: 'insurance', type: 'operation' },
  { code: 'insurance:review', name: '保险申请审核', description: '审核保险申请', module: 'insurance', type: 'operation' },
  { code: 'insurance:delete', name: '保险申请删除', description: '删除保险申请', module: 'insurance', type: 'operation' },

  // 系统管理权限
  { code: 'system:read', name: '系统查看', description: '查看系统信息', module: 'system', type: 'operation' },
  { code: 'system:update', name: '系统更新', description: '更新系统配置', module: 'system', type: 'operation' },
  { code: 'system:admin', name: '系统管理', description: '系统管理操作', module: 'system', type: 'operation' },
  { code: 'system:export', name: '系统导出', description: '导出系统数据', module: 'system', type: 'operation' },

  // 监管任务权限
  { code: 'supervision_tasks:read', name: '监管任务查看', description: '查看监管任务', module: 'supervision', type: 'operation' },
  { code: 'supervision_tasks:create', name: '监管任务创建', description: '创建监管任务', module: 'supervision', type: 'operation' },
  { code: 'supervision_tasks:update', name: '监管任务更新', description: '更新监管任务', module: 'supervision', type: 'operation' },
  { code: 'supervision_tasks:delete', name: '监管任务删除', description: '删除监管任务', module: 'supervision', type: 'operation' },

  // 监管任务完成权限
  { code: 'regulatory_task:read', name: '监管任务完成查看', description: '查看监管任务完成情况', module: 'regulatory', type: 'operation' },
  { code: 'regulatory_task:create', name: '监管任务完成创建', description: '创建监管任务完成记录', module: 'regulatory', type: 'operation' },
  { code: 'regulatory_task:update', name: '监管任务完成更新', description: '更新监管任务完成记录', module: 'regulatory', type: 'operation' },
  { code: 'regulatory_task:delete', name: '监管任务完成删除', description: '删除监管任务完成记录', module: 'regulatory', type: 'operation' },
  { code: 'regulatory_task:review', name: '监管任务完成审核', description: '审核监管任务完成记录', module: 'regulatory', type: 'operation' },

  // 安装任务权限
  { code: 'installation_tasks:read', name: '安装任务查看', description: '查看安装任务', module: 'installation', type: 'operation' },
  { code: 'installation_tasks:create', name: '安装任务创建', description: '创建安装任务', module: 'installation', type: 'operation' },
  { code: 'installation_tasks:update', name: '安装任务更新', description: '更新安装任务', module: 'installation', type: 'operation' },
  { code: 'installation_tasks:delete', name: '安装任务删除', description: '删除安装任务', module: 'installation', type: 'operation' },

  // 生资理赔权限
  { code: 'livestock_claim:read', name: '生资理赔查看', description: '查看生资理赔', module: 'livestock', type: 'operation' },
  { code: 'livestock_claim:create', name: '生资理赔创建', description: '创建生资理赔', module: 'livestock', type: 'operation' },
  { code: 'livestock_claim:review', name: '生资理赔审核', description: '审核生资理赔', module: 'livestock', type: 'operation' },
  { code: 'livestock_claim:payment', name: '生资理赔支付', description: '处理生资理赔支付', module: 'livestock', type: 'operation' },

  // 设备管理权限
  { code: 'device:read', name: '设备查看', description: '查看设备信息', module: 'device', type: 'operation' },
  { code: 'device:create', name: '设备创建', description: '创建设备', module: 'device', type: 'operation' },
  { code: 'device:update', name: '设备更新', description: '更新设备信息', module: 'device', type: 'operation' },
  { code: 'device:delete', name: '设备删除', description: '删除设备', module: 'device', type: 'operation' },

  // 设备告警权限
  { code: 'device_alerts:read', name: '设备告警查看', description: '查看设备告警', module: 'device', type: 'operation' },
  { code: 'device_alerts:create', name: '设备告警创建', description: '创建设备告警', module: 'device', type: 'operation' },
  { code: 'device_alerts:update', name: '设备告警更新', description: '更新设备告警', module: 'device', type: 'operation' },
  { code: 'device_alerts:delete', name: '设备告警删除', description: '删除设备告警', module: 'device', type: 'operation' },

  // 理赔管理权限
  { code: 'claim:read', name: '理赔查看', description: '查看理赔信息', module: 'claim', type: 'operation' },
  { code: 'claim:create', name: '理赔创建', description: '创建理赔', module: 'claim', type: 'operation' },
  { code: 'claim:update', name: '理赔更新', description: '更新理赔信息', module: 'claim', type: 'operation' },
  { code: 'claim:delete', name: '理赔删除', description: '删除理赔', module: 'claim', type: 'operation' },
  { code: 'claim:review', name: '理赔审核', description: '审核理赔', module: 'claim', type: 'operation' },

  // 数据仓库权限
  { code: 'data_warehouse:read', name: '数据仓库查看', description: '查看数据仓库', module: 'data', type: 'operation' },
  { code: 'data_warehouse:export', name: '数据仓库导出', description: '导出数据仓库数据', module: 'data', type: 'operation' }
];

async function addMissingPermissions() {
  try {
    console.log('开始添加缺失的权限...');
    
    // 获取现有权限
    const existingPermissions = await Permission.findAll({
      attributes: ['code']
    });
    const existingCodes = existingPermissions.map(p => p.code);
    
    // 过滤出需要添加的权限
    const permissionsToAdd = missingPermissions.filter(p => !existingCodes.includes(p.code));
    
    console.log(`找到 ${permissionsToAdd.length} 个需要添加的权限`);
    
    if (permissionsToAdd.length === 0) {
      console.log('所有权限都已存在，无需添加');
      return;
    }
    
    // 批量创建权限
    const createdPermissions = await Permission.bulkCreate(permissionsToAdd, {
      ignoreDuplicates: true
    });
    
    console.log(`成功创建 ${createdPermissions.length} 个权限`);
    
    // 获取admin角色
    const adminRole = await Role.findOne({
      where: { name: 'admin' }
    });
    
    if (!adminRole) {
      console.log('未找到admin角色，跳过权限分配');
      return;
    }
    
    console.log(`找到admin角色，ID: ${adminRole.id}`);
    
    // 获取新创建的权限ID
    const newPermissions = await Permission.findAll({
      where: {
        code: {
          [Op.in]: permissionsToAdd.map(p => p.code)
        }
      }
    });
    
    // 为admin角色分配新权限
    const rolePermissions = newPermissions.map(permission => ({
      role_id: adminRole.id,
      permission_id: permission.id,
      granted: true,
      granted_by: 1, // 假设用户ID为1
      granted_at: new Date()
    }));
    
    await RolePermission.bulkCreate(rolePermissions, {
      ignoreDuplicates: true
    });
    
    console.log(`成功为admin角色分配 ${rolePermissions.length} 个权限`);
    
    console.log('权限添加完成！');
    
  } catch (error) {
    console.error('添加权限失败:', error);
  }
}

// 运行脚本
addMissingPermissions().then(() => {
  console.log('脚本执行完成');
  process.exit(0);
}).catch(error => {
  console.error('脚本执行失败:', error);
  process.exit(1);
});
