import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatTableModule } from '@angular/material/table';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatDialogModule, MatDialog } from '@angular/material/dialog';
import { MatSortModule } from '@angular/material/sort';
import { UserDialogComponent } from './user-dialog/user-dialog'; // @ts-ignore: Component used in code but not in template
import { RoleDialogComponent } from './role-dialog/role-dialog'; // @ts-ignore: Component used in code but not in template

interface User {
  id: string;
  username: string;
  realName: string;
  email: string;
  phone: string;
  role: string;
  department: string;
  status: 'active' | 'inactive';
  createdAt: string;
  lastLogin: string;
}

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

@Component({
  selector: 'app-user-management',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    FormsModule,
    MatButtonModule,
    MatIconModule,
    MatTableModule,
    MatInputModule,
    MatSelectModule,
    MatPaginatorModule,
    MatDialogModule,
    MatSortModule
  ],
  templateUrl: './user-management.html',
  styleUrl: './user-management.scss'
})
export class UserManagement implements OnInit {
  // 提供Math对象给模板使用
  readonly Math = Math;
  
  // 用户相关数据
  users = signal<User[]>([]);
  filteredUsers = signal<User[]>([]);
  userSearchTerm = '';
  userRoleFilter = '';
  userStatusFilter = '';
  userSortColumn = 'createdAt';
  userSortDirection = 'desc';
  userPageSize = 10;
  userCurrentPage = 0;

  // 角色相关数据
  roles = signal<Role[]>([]);
  filteredRoles = signal<Role[]>([]);
  roleSearchTerm = '';
  roleSortColumn = 'name';
  roleSortDirection = 'asc';
  rolePageSize = 10;
  roleCurrentPage = 0;

  // 当前激活的标签页
  activeTab = 'users';

  // 角色列表（用于下拉选择）
  roleList: string[] = [];

  // 状态颜色映射
  statusColors: Record<string, string> = {
    'active': '#00B42A',
    'inactive': '#F53F3F'
  };

  // 状态文本映射
  statusTexts: Record<string, string> = {
    'active': '激活',
    'inactive': '禁用'
  };

  constructor(private dialog: MatDialog) {}

  ngOnInit(): void {
    this.loadUsers();
    this.loadRoles();
  }

  loadUsers(): void {
    // 模拟用户数据
    this.users.set([
      {
        id: '1',
        username: 'admin',
        realName: '超级管理员',
        email: 'admin@example.com',
        phone: '13800138000',
        role: '超级管理员',
        department: '管理层',
        status: 'active',
        createdAt: '2025-01-01',
        lastLogin: '2025-09-15 14:30'
      },
      {
        id: '2',
        username: 'customer_service_1',
        realName: '客服小李',
        email: 'cs1@example.com',
        phone: '13800138001',
        role: '客服',
        department: '客户服务部',
        status: 'active',
        createdAt: '2025-02-15',
        lastLogin: '2025-09-15 10:15'
      },
      {
        id: '3',
        username: 'designer_1',
        realName: '张设计师',
        email: 'designer1@example.com',
        phone: '13800138002',
        role: '设计师',
        department: '设计部',
        status: 'active',
        createdAt: '2025-03-10',
        lastLogin: '2025-09-14 16:45'
      },
      {
        id: '4',
        username: 'team_leader_1',
        realName: '王组长',
        email: 'leader1@example.com',
        phone: '13800138003',
        role: '组长',
        department: '设计部',
        status: 'active',
        createdAt: '2025-02-20',
        lastLogin: '2025-09-15 09:00'
      },
      {
        id: '5',
        username: 'finance_1',
        realName: '财务小陈',
        email: 'finance1@example.com',
        phone: '13800138004',
        role: '财务',
        department: '财务部',
        status: 'active',
        createdAt: '2025-03-05',
        lastLogin: '2025-09-13 15:20'
      },
      {
        id: '6',
        username: 'hr_1',
        realName: '人事小郑',
        email: 'hr1@example.com',
        phone: '13800138005',
        role: '人事',
        department: '人力资源部',
        status: 'active',
        createdAt: '2025-03-20',
        lastLogin: '2025-09-14 11:30'
      },
      {
        id: '7',
        username: 'designer_2',
        realName: '刘设计师',
        email: 'designer2@example.com',
        phone: '13800138006',
        role: '设计师',
        department: '设计部',
        status: 'active',
        createdAt: '2025-04-01',
        lastLogin: '2025-09-15 13:45'
      },
      {
        id: '8',
        username: 'designer_3',
        realName: '陈设计师',
        email: 'designer3@example.com',
        phone: '13800138007',
        role: '设计师',
        department: '设计部',
        status: 'inactive',
        createdAt: '2025-04-15',
        lastLogin: '2025-08-20 10:00'
      },
      {
        id: '9',
        username: 'customer_service_2',
        realName: '客服小王',
        email: 'cs2@example.com',
        phone: '13800138008',
        role: '客服',
        department: '客户服务部',
        status: 'active',
        createdAt: '2025-05-01',
        lastLogin: '2025-09-15 11:20'
      },
      {
        id: '10',
        username: 'team_leader_2',
        realName: '李组长',
        email: 'leader2@example.com',
        phone: '13800138009',
        role: '组长',
        department: '设计部',
        status: 'active',
        createdAt: '2025-04-20',
        lastLogin: '2025-09-15 08:45'
      }
    ]);
    
    this.applyUserFilters();
  }

  loadRoles(): void {
    // 模拟角色数据
    this.roles.set([
      {
        id: '1',
        name: '超级管理员',
        description: '系统最高权限管理员，可访问和管理所有功能',
        permissions: ['system:admin', 'project:manage', 'user:manage', 'role:manage', 'finance:view', 'log:view', 'api:manage'],
        usersCount: 1
      },
      {
        id: '2',
        name: '客服',
        description: '负责客户咨询、项目跟进等工作',
        permissions: ['project:view', 'customer:manage', 'case:view'],
        usersCount: 2
      },
      {
        id: '3',
        name: '设计师',
        description: '负责项目设计、任务执行等工作',
        permissions: ['project:view', 'task:manage', 'file:upload'],
        usersCount: 3
      },
      {
        id: '4',
        name: '组长',
        description: '负责团队管理、项目审核等工作',
        permissions: ['project:manage', 'user:view', 'quality:manage', 'team:manage'],
        usersCount: 2
      },
      {
        id: '5',
        name: '财务',
        description: '负责财务数据管理、报表生成等工作',
        permissions: ['finance:manage', 'project:view'],
        usersCount: 1
      },
      {
        id: '6',
        name: '人事',
        description: '负责人事管理、考勤统计等工作',
        permissions: ['hr:manage', 'user:view'],
        usersCount: 1
      }
    ]);
    
    // 更新角色列表
    this.roleList = this.roles().map(role => role.name);
    
    this.applyRoleFilters();
  }

  applyUserFilters(): void {
    let result = [...this.users()];
    
    // 搜索过滤
    if (this.userSearchTerm) {
      const term = this.userSearchTerm.toLowerCase();
      result = result.filter(user => 
        user.username.toLowerCase().includes(term) ||
        user.realName.toLowerCase().includes(term) ||
        user.email.toLowerCase().includes(term) ||
        user.phone.includes(term)
      );
    }
    
    // 角色过滤
    if (this.userRoleFilter) {
      result = result.filter(user => user.role === this.userRoleFilter);
    }
    
    // 状态过滤
    if (this.userStatusFilter) {
      result = result.filter(user => user.status === this.userStatusFilter);
    }
    
    // 排序
    result.sort((a, b) => {
      if (this.userSortColumn === 'createdAt' || this.userSortColumn === 'lastLogin') {
        const dateA = new Date(a[this.userSortColumn]).getTime();
        const dateB = new Date(b[this.userSortColumn]).getTime();
        return this.userSortDirection === 'asc' ? dateA - dateB : dateB - dateA;
      } else {
        const valueA = a[this.userSortColumn as keyof User]?.toString().toLowerCase() || '';
        const valueB = b[this.userSortColumn as keyof User]?.toString().toLowerCase() || '';
        return this.userSortDirection === 'asc' ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
      }
    });
    
    this.filteredUsers.set(result);
  }

  applyRoleFilters(): void {
    let result = [...this.roles()];
    
    // 搜索过滤
    if (this.roleSearchTerm) {
      const term = this.roleSearchTerm.toLowerCase();
      result = result.filter(role => 
        role.name.toLowerCase().includes(term) ||
        role.description.toLowerCase().includes(term)
      );
    }
    
    // 排序
    result.sort((a, b) => {
      const valueA = a[this.roleSortColumn as keyof Role]?.toString().toLowerCase() || '';
      const valueB = b[this.roleSortColumn as keyof Role]?.toString().toLowerCase() || '';
      return this.roleSortDirection === 'asc' ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
    });
    
    this.filteredRoles.set(result);
  }

  // 用户管理方法
  onUserSearch(): void {
    this.applyUserFilters();
  }

  onUserRoleFilterChange(): void {
    this.applyUserFilters();
  }

  onUserStatusFilterChange(): void {
    this.applyUserFilters();
  }

  onUserSort(column: string): void {
    if (this.userSortColumn === column) {
      this.userSortDirection = this.userSortDirection === 'asc' ? 'desc' : 'asc';
    } else {
      this.userSortColumn = column;
      this.userSortDirection = 'asc';
    }
    this.applyUserFilters();
  }

  // 角色管理方法
  onRoleSearch(): void {
    this.applyRoleFilters();
  }

  onRoleSort(column: string): void {
    if (this.roleSortColumn === column) {
      this.roleSortDirection = this.roleSortDirection === 'asc' ? 'desc' : 'asc';
    } else {
      this.roleSortColumn = column;
      this.roleSortDirection = 'asc';
    }
    this.applyRoleFilters();
  }

  // 对话框方法
  openUserDialog(user?: User): void {
    const dialogRef = this.dialog.open(UserDialogComponent, {
      width: '600px',
      data: user ? { ...user } : {
        id: '',
        username: '',
        realName: '',
        email: '',
        phone: '',
        role: '',
        department: '',
        status: 'active',
        createdAt: new Date().toISOString().split('T')[0],
        lastLogin: ''
      }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        if (result.id) {
          // 更新用户
          this.updateUser(result);
        } else {
          // 创建新用户
          this.createUser(result);
        }
      }
    });
  }

  openRoleDialog(role?: Role): void {
    const dialogRef = this.dialog.open(RoleDialogComponent, {
      width: '600px',
      data: role ? { ...role } : {
        id: '',
        name: '',
        description: '',
        permissions: [],
        usersCount: 0
      }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        if (result.id) {
          // 更新角色
          this.updateRole(result);
        } else {
          // 创建新角色
          this.createRole(result);
        }
      }
    });
  }

  // 用户操作方法
  createUser(userData: Omit<User, 'id' | 'lastLogin'>): void {
    const newUser: User = {
      ...userData,
      id: (this.users().length + 1).toString(),
      lastLogin: ''
    };
    
    this.users.set([newUser, ...this.users()]);
    this.applyUserFilters();
  }

  updateUser(updatedUser: User): void {
    this.users.set(this.users().map(user => 
      user.id === updatedUser.id ? updatedUser : user
    ));
    this.applyUserFilters();
  }

  deleteUser(id: string): void {
    if (confirm('确定要删除这个用户吗？')) {
      this.users.set(this.users().filter(user => user.id !== id));
      this.applyUserFilters();
    }
  }

  // 角色操作方法
  createRole(roleData: Omit<Role, 'id' | 'usersCount'>): void {
    const newRole: Role = {
      ...roleData,
      id: (this.roles().length + 1).toString(),
      usersCount: 0
    };
    
    this.roles.set([newRole, ...this.roles()]);
    this.roleList = this.roles().map(role => role.name);
    this.applyRoleFilters();
  }

  updateRole(updatedRole: Role): void {
    this.roles.set(this.roles().map(role => 
      role.id === updatedRole.id ? updatedRole : role
    ));
    this.roleList = this.roles().map(role => role.name);
    this.applyRoleFilters();
  }

  deleteRole(id: string): void {
    // 检查是否有用户正在使用该角色
    const role = this.roles().find(r => r.id === id);
    if (role && role.usersCount > 0) {
      alert('该角色下有用户正在使用，无法删除！');
      return;
    }
    
    if (confirm('确定要删除这个角色吗？')) {
      this.roles.set(this.roles().filter(role => role.id !== id));
      this.roleList = this.roles().map(role => role.name);
      this.applyRoleFilters();
    }
  }

  // 分页相关方法
  get paginatedUsers(): User[] {
    const startIndex = this.userCurrentPage * this.userPageSize;
    return this.filteredUsers().slice(startIndex, startIndex + this.userPageSize);
  }

  // 获取活跃用户数量
  get activeUsersCount() {
    return this.users().filter(u => u.status === 'active').length;
  }
  
  // 获取活跃用户百分比
  get activeUsersPercentage() {
    const allUsers = this.users().length;
    if (allUsers === 0) return 0;
    return Math.round((this.activeUsersCount / allUsers) * 100);
  }

  get totalUserPages(): number {
    return Math.ceil(this.filteredUsers().length / this.userPageSize);
  }

  onUserPageChange(page: number): void {
    this.userCurrentPage = page;
  }

  get paginatedRoles(): Role[] {
    const startIndex = this.roleCurrentPage * this.rolePageSize;
    return this.filteredRoles().slice(startIndex, startIndex + this.rolePageSize);
  }

  get totalRolePages(): number {
    return Math.ceil(this.filteredRoles().length / this.rolePageSize);
  }

  onRolePageChange(page: number): void {
    this.roleCurrentPage = page;
  }

  // 标签页切换
  switchTab(tab: string): void {
    this.activeTab = tab;
  }

  // 辅助方法
  getPageNumbers(totalPages: number, currentPage: number): number[] {
    const pageNumbers = [];
    const maxVisiblePages = 5;
    let startPage = Math.max(0, Math.min(currentPage - Math.floor(maxVisiblePages / 2), totalPages - maxVisiblePages));
    
    for (let i = startPage; i < Math.min(startPage + maxVisiblePages, totalPages); i++) {
      pageNumbers.push(i);
    }
    
    return pageNumbers;
  }
}