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

/**
 * 角色权限管理控制器
 * 专门处理角色权限的分配、管理和动态调用
 */
class RolePermissionController {

  /**
   * 获取所有角色及其权限
   */
  async getAllRolesWithPermissions(req, res) {
    try {
      const roles = await Role.findAll({
        order: [['id', 'ASC']]
      });

      const rolesData = await Promise.all(roles.map(async (role) => {
        // 从RolePermission表获取权限
        const rolePermissions = await RolePermission.findAll({
          where: { 
            role_id: role.id,
            granted: true 
          },
          include: [{
            model: Permission,
            as: 'permission',
            attributes: ['id', 'name', 'code', 'description', 'module', 'type']
          }]
        });

        const permissions = rolePermissions.map(rp => rp.permission.code);
        
        return {
          id: role.id,
          name: role.name,
          description: role.description,
          status: role.status,
          permissions: permissions,
          permissionCount: permissions.length
        };
      }));

      res.json(responseFormat.success({
        roles: rolesData,
        total: rolesData.length
      }, '获取角色权限列表成功'));
    } catch (error) {
      console.error('获取角色权限列表失败:', error);
      res.status(500).json(responseFormat.error('获取角色权限列表失败'));
    }
  }

  /**
   * 获取所有权限
   */
  async getAllPermissions(req, res) {
    try {
      const permissions = await Permission.findAll({
        order: [['id', 'ASC']]
      });

      res.json(responseFormat.success(permissions, '获取权限列表成功'));
    } catch (error) {
      console.error('获取权限列表失败:', error);
      res.status(500).json(responseFormat.error('获取权限列表失败'));
    }
  }

  /**
   * 获取指定角色的权限详情
   */
  async getRolePermissionDetail(req, res) {
    try {
      const { roleId } = req.params;
      console.log('获取角色权限详情，角色ID:', roleId);

      const role = await Role.findByPk(roleId);
      console.log('角色查询结果:', role ? role.name : '未找到');

      if (!role) {
        return res.status(404).json(responseFormat.error('角色不存在'));
      }

      // 获取所有权限用于对比
      const allPermissions = await Permission.findAll({
        attributes: ['id', 'name', 'code', 'description', 'module', 'type', 'parent_id'],
        order: [['module', 'ASC'], ['id', 'ASC']]
      });
      console.log('权限查询结果:', allPermissions.length, '个权限');

      // 从RolePermission表获取角色已分配的权限
      const rolePermissions = await RolePermission.findAll({
        where: { 
          role_id: roleId,
          granted: true 
        },
        include: [{
          model: Permission,
          as: 'permission',
          attributes: ['id', 'name', 'code', 'description', 'module', 'type']
        }]
      });

      const assignedPermissionCodes = rolePermissions.map(rp => rp.permission.code);
      console.log('已分配权限代码:', assignedPermissionCodes.length, '个');

      // 暂时返回简化数据，不构建权限树
      res.json(responseFormat.success({
        role: {
          id: role.id,
          name: role.name,
          description: role.description,
          status: role.status
        },
        assignedPermissions: assignedPermissionCodes,
        allPermissions: allPermissions.map(p => ({
          id: p.id,
          name: p.name,
          code: p.code,
          description: p.description,
          module: p.module,
          type: p.type,
          parent_id: p.parent_id,
          assigned: assignedPermissionCodes.includes(p.code)
        })),
        assignedCount: assignedPermissionCodes.length,
        totalCount: allPermissions.length
      }, '获取角色权限详情成功'));
    } catch (error) {
      console.error('获取角色权限详情失败:', error);
      console.error('错误堆栈:', error.stack);
      res.status(500).json(responseFormat.error('获取角色权限详情失败'));
    }
  }

  /**
   * 批量分配角色权限
   */
  async batchAssignPermissions(req, res) {
    try {
      const { roleId } = req.params;
      const { permissionIds, operation = 'replace' } = req.body;

      console.log('=== 批量分配权限开始 ===');
      console.log('角色ID:', roleId);
      console.log('权限ID列表:', permissionIds);
      console.log('操作类型:', operation);
      console.log('请求体:', JSON.stringify(req.body, null, 2));

      if (!Array.isArray(permissionIds)) {
        console.log('❌ 权限ID列表格式错误');
        return res.status(400).json(responseFormat.error('权限ID列表格式错误'));
      }

      const role = await Role.findByPk(roleId);
      if (!role) {
        console.log('❌ 角色不存在');
        return res.status(404).json(responseFormat.error('角色不存在'));
      }
      
      console.log('找到角色:', role.name);

      // 验证权限ID是否存在
      const validPermissions = await Permission.findAll({
        where: { id: { [Op.in]: permissionIds } },
        attributes: ['id']
      });

      const validPermissionIds = validPermissions.map(p => p.id);
      const invalidIds = permissionIds.filter(id => !validPermissionIds.includes(id));

      console.log('有效权限ID:', validPermissionIds);
      console.log('无效权限ID:', invalidIds);

      if (invalidIds.length > 0) {
        console.log('❌ 存在无效的权限ID');
        return res.status(400).json(responseFormat.error(`无效的权限ID: ${invalidIds.join(', ')}`));
      }

      // 根据操作类型处理权限分配
      if (operation === 'replace') {
        console.log('执行替换模式权限分配');
        
        // 替换模式：删除现有权限，添加新权限
        const deletedCount = await RolePermission.destroy({ where: { role_id: roleId } });
        console.log('删除现有权限数量:', deletedCount);
        
        if (permissionIds.length > 0) {
          const rolePermissions = permissionIds.map(permissionId => ({
            role_id: roleId,
            permission_id: permissionId,
            granted: true
          }));
          console.log('准备创建的权限记录:', rolePermissions);
          
          const createdPermissions = await RolePermission.bulkCreate(rolePermissions);
          console.log('成功创建的权限记录数量:', createdPermissions.length);
        }
      } else if (operation === 'add') {
        // 添加模式：只添加新权限
        const existingPermissions = await RolePermission.findAll({
          where: { role_id: roleId },
          attributes: ['permission_id']
        });
        const existingIds = existingPermissions.map(p => p.permission_id);
        const newPermissionIds = permissionIds.filter(id => !existingIds.includes(id));

        if (newPermissionIds.length > 0) {
          const rolePermissions = newPermissionIds.map(permissionId => ({
            role_id: roleId,
            permission_id: permissionId,
            granted: true
          }));
          await RolePermission.bulkCreate(rolePermissions);
        }
      } else if (operation === 'remove') {
        // 移除模式：删除指定权限
        await RolePermission.destroy({
          where: {
            role_id: roleId,
            permission_id: { [Op.in]: permissionIds }
          }
        });
      }

      console.log('✅ 权限分配完成');
      res.json(responseFormat.success(null, `${operation === 'replace' ? '替换' : operation === 'add' ? '添加' : '移除'}角色权限成功`));
    } catch (error) {
      console.error('❌ 批量分配权限失败:', error);
      console.error('错误堆栈:', error.stack);
      res.status(500).json(responseFormat.error('批量分配角色权限失败'));
    }
    
    console.log('=== 批量分配权限结束 ===');
  }

  /**
   * 复制角色权限
   */
  async copyRolePermissions(req, res) {
    try {
      const { sourceRoleId, targetRoleId } = req.body;

      if (!sourceRoleId || !targetRoleId) {
        return res.status(400).json(responseFormat.error('源角色ID和目标角色ID不能为空'));
      }

      if (sourceRoleId === targetRoleId) {
        return res.status(400).json(responseFormat.error('源角色和目标角色不能相同'));
      }

      // 验证角色存在
      const [sourceRole, targetRole] = await Promise.all([
        Role.findByPk(sourceRoleId),
        Role.findByPk(targetRoleId)
      ]);

      if (!sourceRole) {
        return res.status(404).json(responseFormat.error('源角色不存在'));
      }
      if (!targetRole) {
        return res.status(404).json(responseFormat.error('目标角色不存在'));
      }

      // 获取源角色的权限
      const sourcePermissions = await RolePermission.findAll({
        where: { role_id: sourceRoleId },
        attributes: ['permission_id']
      });

      // 删除目标角色现有权限
      await RolePermission.destroy({ where: { role_id: targetRoleId } });

      // 复制权限到目标角色
      if (sourcePermissions.length > 0) {
        const targetPermissions = sourcePermissions.map(p => ({
          role_id: targetRoleId,
          permission_id: p.permission_id,
          granted: true
        }));
        await RolePermission.bulkCreate(targetPermissions);
      }

      res.json(responseFormat.success(null, `成功将 ${sourceRole.name} 的权限复制到 ${targetRole.name}`));
    } catch (error) {
      console.error('复制角色权限失败:', error);
      res.status(500).json(responseFormat.error('复制角色权限失败'));
    }
  }

  /**
   * 检查用户权限
   */
  async checkUserPermission(req, res) {
    try {
      const { userId, permissionCode } = req.params;

      const user = await User.findByPk(userId, {
        include: [
          {
            model: Role,
            as: 'role',
            include: [
              {
                model: Permission,
                as: 'rolePermissions',
                where: { code: permissionCode },
                required: false,
                through: {
                  attributes: ['granted']
                }
              }
            ]
          }
        ]
      });

      if (!user) {
        return res.status(404).json(responseFormat.error('用户不存在'));
      }

      const hasPermission = user.role && 
                           user.role.rolePermissions && 
                           user.role.rolePermissions.length > 0 &&
                           user.role.rolePermissions[0].RolePermission.granted;

      res.json(responseFormat.success({
        userId: user.id,
        username: user.username,
        roleName: user.role ? user.role.name : null,
        permissionCode,
        hasPermission,
        checkTime: new Date()
      }, '权限检查完成'));
    } catch (error) {
      console.error('检查用户权限失败:', error);
      res.status(500).json(responseFormat.error('检查用户权限失败'));
    }
  }

  /**
   * 获取权限统计信息
   */
  async getPermissionStats(req, res) {
    try {
      // 统计各种数据
      const [
        totalRoles,
        totalPermissions,
        moduleStats,
        roles
      ] = await Promise.all([
        Role.count(),
        Permission.count(),
        Permission.findAll({
          attributes: [
            'module',
            [Permission.sequelize.fn('COUNT', Permission.sequelize.col('id')), 'count']
          ],
          group: ['module'],
          order: [['module', 'ASC']]
        }),
        Role.findAll({
          attributes: ['id', 'name', 'permissions'],
          order: [['name', 'ASC']]
        })
      ]);

      // 计算总分配数和角色权限分布
      let totalAssignments = 0;
      const roleDistribution = roles.map(role => {
        let permissions = [];
        if (Array.isArray(role.permissions)) {
          permissions = role.permissions;
        } else if (typeof role.permissions === 'string') {
          try {
            permissions = JSON.parse(role.permissions);
          } catch (e) {
            permissions = [];
          }
        }
        
        const permissionCount = permissions.length;
        totalAssignments += permissionCount;
        return {
          roleId: role.id,
          roleName: role.name,
          permissionCount
        };
      });

      res.json(responseFormat.success({
        overview: {
          totalRoles,
          totalPermissions,
          totalAssignments,
          averagePermissionsPerRole: totalRoles > 0 ? Math.round(totalAssignments / totalRoles) : 0
        },
        moduleDistribution: moduleStats.map(stat => ({
          module: stat.module,
          count: parseInt(stat.dataValues.count)
        })),
        roleDistribution
      }, '获取权限统计成功'));
    } catch (error) {
      console.error('获取权限统计失败:', error);
      res.status(500).json(responseFormat.error('获取权限统计失败'));
    }
  }

  /**
   * 构建权限树
   */
  buildPermissionTree(permissions, parentId = null) {
    const tree = [];
    for (const permission of permissions) {
      if (permission.parent_id === parentId) {
        const children = this.buildPermissionTree(permissions, permission.id);
        const node = {
          ...(permission.toJSON ? permission.toJSON() : permission),
          children: children.length > 0 ? children : undefined
        };
        tree.push(node);
      }
    }
    return tree;
  }

  /**
   * 标记已分配的权限
   */
  markAssignedPermissions(permissions, assignedIds) {
    return permissions.map(permission => ({
      ...permission,
      assigned: assignedIds.includes(permission.id),
      children: permission.children ? 
        this.markAssignedPermissions(permission.children, assignedIds) : 
        undefined
    }));
  }

  /**
   * 根据权限代码标记已分配的权限
   */
  markAssignedPermissionsByCode(permissions, assignedCodes) {
    return permissions.map(permission => ({
      ...permission,
      assigned: assignedCodes.includes(permission.code),
      children: permission.children ? 
        this.markAssignedPermissionsByCode(permission.children, assignedCodes) : 
        undefined
    }));
  }
}

module.exports = new RolePermissionController();