import { Component, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { MatCheckboxModule } from '@angular/material/checkbox';

interface Role {
  id: string;
  name: string;
  description: string;
  permissions: string[];
  usersCount: number;
}

interface PermissionGroup {
  name: string;
  permissions: Permission[];
}

interface Permission {
  key: string;
  name: string;
  description: string;
}

@Component({
  selector: 'app-role-dialog',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatButtonModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatIconModule,
    MatCheckboxModule
  ],
  templateUrl: './role-dialog.html',
  styleUrl: './role-dialog.scss'
})
export class RoleDialogComponent {
  role: Role;
  isEditMode: boolean;
  
  // 权限组列表
  permissionGroups: PermissionGroup[] = [
    {
      name: '系统管理',
      permissions: [
        { key: 'system:admin', name: '超级管理员权限', description: '拥有系统内所有功能的完全访问权限' },
        { key: 'system:view', name: '系统概览', description: '查看系统整体运行状态和统计数据' }
      ]
    },
    {
      name: '项目管理',
      permissions: [
        { key: 'project:manage', name: '项目管理', description: '创建、编辑、删除和分配项目' },
        { key: 'project:view', name: '项目查看', description: '查看项目详情和进度' },
        { key: 'project:review', name: '项目审核', description: '审核和审批项目设计方案' },
        { key: 'project:quality', name: '质量管理', description: '管理项目质量和验收流程' }
      ]
    },
    {
      name: '用户管理',
      permissions: [
        { key: 'user:manage', name: '用户管理', description: '创建、编辑、删除用户账号' },
        { key: 'user:view', name: '用户查看', description: '查看用户信息和状态' },
        { key: 'role:manage', name: '角色管理', description: '创建、编辑、删除角色和权限' }
      ]
    },
    {
      name: '财务管理',
      permissions: [
        { key: 'finance:manage', name: '财务管理', description: '管理项目预算、收支和结算' },
        { key: 'finance:view', name: '财务查看', description: '查看财务报表和统计数据' },
        { key: 'finance:export', name: '财务导出', description: '导出财务数据和报表' }
      ]
    },
    {
      name: '客户管理',
      permissions: [
        { key: 'customer:manage', name: '客户管理', description: '创建、编辑、删除客户信息' },
        { key: 'customer:view', name: '客户查看', description: '查看客户信息和历史记录' },
        { key: 'case:view', name: '案例查看', description: '查看设计案例库' }
      ]
    },
    {
      name: '系统监控',
      permissions: [
        { key: 'log:view', name: '日志查看', description: '查看系统操作日志' },
        { key: 'log:export', name: '日志导出', description: '导出系统操作日志' }
      ]
    },
    {
      name: 'API集成',
      permissions: [
        { key: 'api:manage', name: 'API管理', description: '配置和管理第三方API集成' },
        { key: 'api:view', name: 'API查看', description: '查看API配置和状态' }
      ]
    }
  ];

  constructor(
    public dialogRef: MatDialogRef<RoleDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: Role
  ) {
    this.isEditMode = !!data.id;
    this.role = {
      id: data.id || '',
      name: data.name || '',
      description: data.description || '',
      permissions: data.permissions ? [...data.permissions] : [],
      usersCount: data.usersCount || 0
    };
  }

  onCancel(): void {
    this.dialogRef.close();
  }

  onSave(): void {
    if (this.isFormValid()) {
      this.dialogRef.close(this.role);
    }
  }

  isFormValid(): boolean {
    // 验证角色名称
    if (!this.role.name.trim()) {
      alert('请输入角色名称');
      return false;
    }

    // 验证角色描述
    if (!this.role.description.trim()) {
      alert('请输入角色描述');
      return false;
    }

    // 验证权限选择
    if (this.role.permissions.length === 0 && this.role.name !== '超级管理员') {
      alert('请至少选择一项权限');
      return false;
    }

    // 超级管理员默认拥有所有权限
    if (this.role.name === '超级管理员') {
      const allPermissions = this.permissionGroups
        .flatMap(group => group.permissions)
        .map(permission => permission.key);
      this.role.permissions = allPermissions;
    }

    return true;
  }

  // 权限选择方法
  togglePermission(permissionKey: string): void {
    const index = this.role.permissions.indexOf(permissionKey);
    if (index > -1) {
      // 取消选择
      this.role.permissions.splice(index, 1);
    } else {
      // 添加选择
      this.role.permissions.push(permissionKey);
    }
  }

  // 检查权限是否已选择
  isPermissionSelected(permissionKey: string): boolean {
    return this.role.permissions.includes(permissionKey);
  }

  // 全选/取消全选权限组
  togglePermissionGroup(group: PermissionGroup): void {
    const groupPermissionKeys = group.permissions.map(p => p.key);
    const allSelected = groupPermissionKeys.every(key => this.isPermissionSelected(key));
    
    if (allSelected) {
      // 取消全选
      this.role.permissions = this.role.permissions.filter(key => 
        !groupPermissionKeys.includes(key)
      );
    } else {
      // 全选
      groupPermissionKeys.forEach(key => {
        if (!this.isPermissionSelected(key)) {
          this.role.permissions.push(key);
        }
      });
    }
  }

  // 检查权限组是否全部已选择
  isPermissionGroupSelected(group: PermissionGroup): boolean {
    return group.permissions.every(permission => 
      this.isPermissionSelected(permission.key)
    );
  }

  // 检查权限组是否部分已选择
  isPermissionGroupIndeterminate(group: PermissionGroup): boolean {
    const selectedCount = group.permissions.filter(permission => 
      this.isPermissionSelected(permission.key)
    ).length;
    return selectedCount > 0 && selectedCount < group.permissions.length;
  }

  // 获取当前已选择的权限数量
  get selectedPermissionsCount(): number {
    return this.role.permissions.length;
  }

  // 获取所有可选择的权限数量
  get totalPermissionsCount(): number {
    return this.permissionGroups.flatMap(group => group.permissions).length;
  }
}